-
Notifications
You must be signed in to change notification settings - Fork 372
/
Copy pathatomic_trigger_conditions.py
1483 lines (1123 loc) · 51.9 KB
/
atomic_trigger_conditions.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
# Copyright (c) 2018-2020 Intel Corporation
#
# This work is licensed under the terms of the MIT license.
# For a copy, see <https://opensource.org/licenses/MIT>.
"""
This module provides all atomic scenario behaviors that reflect
trigger conditions to either activate another behavior, or to stop
another behavior.
For example, such a condition could be "InTriggerRegion", which checks
that a given actor reached a certain region on the map, and then starts/stops
a behavior of this actor.
The atomics are implemented with py_trees and make use of the AtomicCondition
base class
"""
from __future__ import print_function
import operator
import datetime
import math
import py_trees
import carla
from agents.navigation.global_route_planner import GlobalRoutePlanner
from srunner.scenariomanager.scenarioatomics.atomic_behaviors import calculate_distance
from srunner.scenariomanager.carla_data_provider import CarlaDataProvider
from srunner.scenariomanager.timer import GameTime
from srunner.tools.scenario_helper import get_distance_along_route, get_distance_between_actors
import srunner.tools as sr_tools
EPSILON = 0.001
class AtomicCondition(py_trees.behaviour.Behaviour):
"""
Base class for all atomic conditions used to setup a scenario
*All behaviors should use this class as parent*
Important parameters:
- name: Name of the atomic condition
"""
def __init__(self, name):
"""
Default init. Has to be called via super from derived class
"""
super(AtomicCondition, self).__init__(name)
self.logger.debug("%s.__init__()" % (self.__class__.__name__))
self.name = name
def setup(self, unused_timeout=15):
"""
Default setup
"""
self.logger.debug("%s.setup()" % (self.__class__.__name__))
return True
def initialise(self):
"""
Initialise setup
"""
self.logger.debug("%s.initialise()" % (self.__class__.__name__))
def terminate(self, new_status):
"""
Default terminate. Can be extended in derived class
"""
self.logger.debug("%s.terminate()[%s->%s]" % (self.__class__.__name__, self.status, new_status))
class IfTriggerer(AtomicCondition):
def __init__(self, actor_ego, actor_npc, comparison_operator=operator.gt, name="IfTriggerer"):
super(IfTriggerer, self).__init__(name)
self.actor_ego = actor_ego
self.actor_npc = actor_npc
self._comparison_operator = comparison_operator
def initialise(self):
super(IfTriggerer, self).initialise()
def update(self):
ego_speed_now = CarlaDataProvider.get_velocity(self.actor_ego)
npc_speed_now = CarlaDataProvider.get_velocity(self.actor_npc)
new_status = py_trees.common.Status.RUNNING
if self._comparison_operator(ego_speed_now, npc_speed_now):
new_status = py_trees.common.Status.SUCCESS
else:
new_status = py_trees.common.Status.INVALID
return new_status
class TimeOfWaitComparison(AtomicCondition):
def __init__(self, duration_time, name="TimeOfWaitComparison"):
super(TimeOfWaitComparison, self).__init__(name)
self._duration_time = duration_time
self._start_time = None
def initialise(self):
self._start_time = GameTime.get_time()
super(TimeOfWaitComparison, self).initialise()
def update(self):
new_status = py_trees.common.Status.RUNNING
_current_time = GameTime.get_time()
if _current_time - self._start_time > self._duration_time:
new_status = py_trees.common.Status.SUCCESS
return new_status
class InTriggerNearCollision(AtomicCondition):
def __init__(self, reference_actor, actor, distance, comparison_operator=operator.lt,
name="InTriggerNearCollision"):
"""
Setup trigger distance
"""
super(InTriggerNearCollision, self).__init__(name)
self.logger.debug("%s.__init__()" % self.__class__.__name__)
self._reference_actor = reference_actor
self._actor = actor
self._distance = distance
self._comparison_operator = comparison_operator
self._control = self._reference_actor.get_control()
def update(self):
"""
Check if the ego vehicle is within trigger distance to other actor
"""
new_status = py_trees.common.Status.RUNNING
location = CarlaDataProvider.get_location(self._actor)
reference_location = CarlaDataProvider.get_location(self._reference_actor)
if location is None or reference_location is None:
return new_status
if self._comparison_operator(calculate_distance(location, reference_location), self._distance):
new_status = py_trees.common.Status.SUCCESS
print("Too close, collision!")
self._control.throttle = 0
self._control.brake = 1
print('decelerate!!!')
self._reference_actor.apply_control(self._control)
self.logger.debug("%s.update()[%s->%s]" % (self.__class__.__name__, self.status, new_status))
return new_status
class InTriggerDistanceToOSCPosition(AtomicCondition):
"""
OpenSCENARIO atomic
This class contains the trigger condition for a distance to an OpenSCENARIO position
Args:
actor (carla.Actor): CARLA actor to execute the behavior
osc_position (str): OpenSCENARIO position
distance (float): Trigger distance between the actor and the target location in meters
name (str): Name of the condition
The condition terminates with SUCCESS, when the actor reached the target distance to the openSCENARIO position
"""
def __init__(self, actor, osc_position, distance, along_route=False,
comparison_operator=operator.lt, name="InTriggerDistanceToOSCPosition"):
"""
Setup parameters
"""
super(InTriggerDistanceToOSCPosition, self).__init__(name)
self._actor = actor
self._osc_position = osc_position
self._distance = distance
self._along_route = along_route
self._comparison_operator = comparison_operator
self._map = CarlaDataProvider.get_map()
if self._along_route:
# Get the global route planner, used to calculate the route
self._grp = GlobalRoutePlanner(self._map, 0.5)
else:
self._grp = None
def initialise(self):
if self._distance < 0:
raise ValueError("distance value must be positive")
def update(self):
"""
Check if actor is in trigger distance
"""
new_status = py_trees.common.Status.RUNNING
# calculate transform with method in openscenario_parser.py
osc_transform = sr_tools.openscenario_parser.OpenScenarioParser.convert_position_to_transform(
self._osc_position)
if osc_transform is not None:
osc_location = osc_transform.location
actor_location = CarlaDataProvider.get_location(self._actor)
if self._along_route:
# Global planner needs a location at a driving lane
actor_location = self._map.get_waypoint(actor_location).transform.location
osc_location = self._map.get_waypoint(osc_location).transform.location
distance = calculate_distance(actor_location, osc_location, self._grp)
if self._comparison_operator(distance, self._distance):
new_status = py_trees.common.Status.SUCCESS
return new_status
class InTimeToArrivalToOSCPosition(AtomicCondition):
"""
OpenSCENARIO atomic
This class contains a trigger if an actor arrives within a given time to an OpenSCENARIO position
Important parameters:
- actor: CARLA actor to execute the behavior
- osc_position: OpenSCENARIO position
- time: The behavior is successful, if TTA is less than _time_ in seconds
- name: Name of the condition
The condition terminates with SUCCESS, when the actor can reach the position within the given time
"""
def __init__(self, actor, osc_position, time, along_route=False,
comparison_operator=operator.lt, name="InTimeToArrivalToOSCPosition"):
"""
Setup parameters
"""
super(InTimeToArrivalToOSCPosition, self).__init__(name)
self._map = CarlaDataProvider.get_map()
self._actor = actor
self._osc_position = osc_position
self._time = float(time)
self._along_route = along_route
self._comparison_operator = comparison_operator
if self._along_route:
# Get the global route planner, used to calculate the route
self._grp = GlobalRoutePlanner(self._map, 0.5)
else:
self._grp = None
def initialise(self):
if self._time < 0:
raise ValueError("time value must be positive")
def update(self):
"""
Check if actor can arrive within trigger time
"""
new_status = py_trees.common.Status.RUNNING
# calculate transform with method in openscenario_parser.py
try:
osc_transform = sr_tools.openscenario_parser.OpenScenarioParser.convert_position_to_transform(
self._osc_position)
except AttributeError:
return py_trees.common.Status.FAILURE
target_location = osc_transform.location
actor_location = CarlaDataProvider.get_location(self._actor)
if target_location is None or actor_location is None:
return new_status
if self._along_route:
# Global planner needs a location at a driving lane
actor_location = self._map.get_waypoint(actor_location).transform.location
target_location = self._map.get_waypoint(target_location).transform.location
distance = calculate_distance(actor_location, target_location, self._grp)
actor_velocity = CarlaDataProvider.get_velocity(self._actor)
# time to arrival
if actor_velocity > 0:
time_to_arrival = distance / actor_velocity
elif distance == 0:
time_to_arrival = 0
else:
time_to_arrival = float('inf')
if self._comparison_operator(time_to_arrival, self._time):
new_status = py_trees.common.Status.SUCCESS
return new_status
class StandStill(AtomicCondition):
"""
This class contains a standstill behavior of a scenario
Important parameters:
- actor: CARLA actor to execute the behavior
- name: Name of the condition
- duration: Duration of the behavior in seconds
The condition terminates with SUCCESS, when the actor does not move
"""
def __init__(self, actor, name, duration=float("inf")):
"""
Setup actor
"""
super(StandStill, self).__init__(name)
self.logger.debug("%s.__init__()" % (self.__class__.__name__))
self._actor = actor
self._duration = duration
self._start_time = 0
def initialise(self):
"""
Initialize the start time of this condition
"""
self._start_time = GameTime.get_time()
super(StandStill, self).initialise()
def update(self):
"""
Check if the _actor stands still (v=0)
"""
new_status = py_trees.common.Status.RUNNING
velocity = CarlaDataProvider.get_velocity(self._actor)
if velocity > 0.1:
self._start_time = GameTime.get_time()
if GameTime.get_time() - self._start_time > self._duration:
new_status = py_trees.common.Status.SUCCESS
self.logger.debug("%s.update()[%s->%s]" % (self.__class__.__name__, self.status, new_status))
return new_status
class RelativeVelocityToOtherActor(AtomicCondition):
"""
Atomic containing a comparison between an actor's velocity
and another actor's one. The behavior returns SUCCESS when the
expected comparison (greater than / less than / equal to) is achieved
Args:
actor (carla.Actor): actor from which the velocity is taken
other_actor (carla.Actor): The actor with the reference velocity
speed (float): Difference of speed between the actors
name (string): Name of the condition
comparison_operator: Type "operator", used to compare the two velocities
"""
def __init__(self, actor, other_actor, speed, comparison_operator=operator.gt,
name="RelativeVelocityToOtherActor"):
"""
Setup the parameters
"""
super(RelativeVelocityToOtherActor, self).__init__(name)
self.logger.debug("%s.__init__()" % (self.__class__.__name__))
self._actor = actor
self._other_actor = other_actor
self._relative_speed = speed
self._comparison_operator = comparison_operator
def update(self):
"""
Gets the speed of the two actors and compares them according to the comparison operator
returns:
py_trees.common.Status.RUNNING when the comparison fails and
py_trees.common.Status.SUCCESS when it succeeds
"""
new_status = py_trees.common.Status.RUNNING
curr_speed = CarlaDataProvider.get_velocity(self._actor)
other_speed = CarlaDataProvider.get_velocity(self._other_actor)
relative_speed = curr_speed - other_speed
if self._comparison_operator(relative_speed, self._relative_speed):
new_status = py_trees.common.Status.SUCCESS
self.logger.debug("%s.update()[%s->%s]" % (self.__class__.__name__, self.status, new_status))
return new_status
class TriggerVelocity(AtomicCondition):
"""
Atomic containing a comparison between an actor's speed and a reference one.
The behavior returns SUCCESS when the expected comparison (greater than /
less than / equal to) is achieved.
Args:
actor (carla.Actor): CARLA actor from which the speed will be taken.
name (string): Name of the atomic
target_velocity (float): velcoity to be compared with the actor's one
comparison_operator: Type "operator", used to compare the two velocities
"""
def __init__(self, actor, target_velocity, comparison_operator=operator.gt, name="TriggerVelocity"):
"""
Setup the atomic parameters
"""
super(TriggerVelocity, self).__init__(name)
self.logger.debug("%s.__init__()" % (self.__class__.__name__))
self._actor = actor
self._target_velocity = target_velocity
self._comparison_operator = comparison_operator
def update(self):
"""
Gets the speed of the actor and compares it with the reference one
returns:
py_trees.common.Status.RUNNING when the comparison fails and
py_trees.common.Status.SUCCESS when it succeeds
"""
new_status = py_trees.common.Status.RUNNING
actor_speed = CarlaDataProvider.get_velocity(self._actor)
if self._comparison_operator(actor_speed, self._target_velocity):
new_status = py_trees.common.Status.SUCCESS
self.logger.debug("%s.update()[%s->%s]" % (self.__class__.__name__, self.status, new_status))
return new_status
class TriggerAcceleration(AtomicCondition):
"""
Atomic containing a comparison between an actor's acceleration
and a reference one. The behavior returns SUCCESS when the
expected comparison (greater than / less than / equal to) is achieved
Args:
actor (carla.Actor): CARLA actor to execute the behavior
name (str): Name of the condition
target_acceleration (float): Acceleration reference (in m/s^2) on which the success is dependent
comparison_operator (operator): Type "operator", used to compare the two acceleration
"""
def __init__(self, actor, target_acceleration, comparison_operator=operator.gt, name="TriggerAcceleration"):
"""
Setup trigger acceleration
"""
super(TriggerAcceleration, self).__init__(name)
self.logger.debug("%s.__init__()" % (self.__class__.__name__))
self._actor = actor
self._target_acceleration = target_acceleration
self._comparison_operator = comparison_operator
def update(self):
"""
Gets the accleration of the actor and compares it with the reference one
returns:
py_trees.common.Status.RUNNING when the comparison fails and
py_trees.common.Status.SUCCESS when it succeeds
"""
new_status = py_trees.common.Status.RUNNING
acceleration = self._actor.get_acceleration()
linear_accel = math.sqrt(math.pow(acceleration.x, 2) +
math.pow(acceleration.y, 2) +
math.pow(acceleration.z, 2))
if self._comparison_operator(linear_accel, self._target_acceleration):
new_status = py_trees.common.Status.SUCCESS
self.logger.debug("%s.update()[%s->%s]" % (self.__class__.__name__, self.status, new_status))
return new_status
class TimeOfDayComparison(AtomicCondition):
"""
Atomic containing a comparison between the current time of day of the simulation
and a given one. The behavior returns SUCCESS when the
expected comparison (greater than / less than / equal to) is achieved
Args:
datetime (datetime): CARLA actor to execute the behavior
name (str): Name of the condition
target_acceleration (float): Acceleration reference (in m/s^2) on which the success is dependent
comparison_operator (operator): Type "operator", used to compare the two acceleration
"""
def __init__(self, dattime, comparison_operator=operator.gt, name="TimeOfDayComparison"):
"""
"""
super(TimeOfDayComparison, self).__init__(name)
self.logger.debug("%s.__init__()" % (self.__class__.__name__))
self._datetime = datetime.datetime.strptime(dattime, "%Y-%m-%dT%H:%M:%S")
self._comparison_operator = comparison_operator
def update(self):
"""
Gets the time of day of the simulation and compares it with the reference one
returns:
py_trees.common.Status.RUNNING when the comparison fails and
py_trees.common.Status.SUCCESS when it succeeds
"""
new_status = py_trees.common.Status.RUNNING
try:
check_dtime = operator.attrgetter("Datetime")
dtime = check_dtime(py_trees.blackboard.Blackboard())
except AttributeError:
pass
if self._comparison_operator(dtime, self._datetime):
new_status = py_trees.common.Status.SUCCESS
self.logger.debug("%s.update()[%s->%s]" % (self.__class__.__name__, self.status, new_status))
return new_status
class OSCStartEndCondition(AtomicCondition):
"""
This class contains a check if a named story element has started/terminated.
Important parameters:
- element_name: The story element's name attribute
- element_type: The element type [act,scene,maneuver,event,action]
- rule: Either START or END
The condition terminates with SUCCESS, when the named story element starts
"""
def __init__(self, element_type, element_name, rule, name="OSCStartEndCondition"):
"""
Setup element details
"""
super(OSCStartEndCondition, self).__init__(name)
self.logger.debug("%s.__init__()" % (self.__class__.__name__))
self._element_type = element_type.upper()
self._element_name = element_name
self._rule = rule.upper()
self._start_time = None
self._blackboard = py_trees.blackboard.Blackboard()
def initialise(self):
"""
Initialize the start time of this condition
"""
self._start_time = GameTime.get_time()
super(OSCStartEndCondition, self).initialise()
def update(self):
"""
Check if the specified story element has started/ended since the beginning of the condition
"""
new_status = py_trees.common.Status.RUNNING
if new_status == py_trees.common.Status.RUNNING:
blackboard_variable_name = "({}){}-{}".format(self._element_type, self._element_name, self._rule)
element_start_time = self._blackboard.get(blackboard_variable_name)
if element_start_time and element_start_time >= self._start_time:
new_status = py_trees.common.Status.SUCCESS
self.logger.debug("%s.update()[%s->%s]" % (self.__class__.__name__, self.status, new_status))
return new_status
class InTriggerRegion(AtomicCondition):
"""
This class contains the trigger region (condition) of a scenario
Important parameters:
- actor: CARLA actor to execute the behavior
- name: Name of the condition
- min_x, max_x, min_y, max_y: bounding box of the trigger region
The condition terminates with SUCCESS, when the actor reached the target region
"""
def __init__(self, actor, min_x, max_x, min_y, max_y, name="TriggerRegion"):
"""
Setup trigger region (rectangle provided by
[min_x,min_y] and [max_x,max_y]
"""
super(InTriggerRegion, self).__init__(name)
self.logger.debug("%s.__init__()" % (self.__class__.__name__))
self._actor = actor
self._min_x = min_x
self._max_x = max_x
self._min_y = min_y
self._max_y = max_y
def update(self):
"""
Check if the _actor location is within trigger region
"""
new_status = py_trees.common.Status.RUNNING
location = CarlaDataProvider.get_location(self._actor)
if location is None:
return new_status
not_in_region = (location.x < self._min_x or location.x > self._max_x) or \
(location.y < self._min_y or location.y > self._max_y)
if not not_in_region:
new_status = py_trees.common.Status.SUCCESS
self.logger.debug("%s.update()[%s->%s]" % (self.__class__.__name__, self.status, new_status))
return new_status
class InTriggerDistanceToVehicle(AtomicCondition):
"""
This class contains the trigger distance (condition) between to actors
of a scenario
Important parameters:
- actor: CARLA actor to execute the behavior
- reference_actor: Reference CARLA actor
- name: Name of the condition
- distance: Trigger distance between the two actors in meters
- distance_type: Specifies how distance should be calculated between the two actors
- freespace: if True distance is calculated between closest boundary points else it will be from center-center
- dx, dy, dz: distance to reference_location (location of reference_actor)
The condition terminates with SUCCESS, when the actor reached the target distance to the other actor
"""
def __init__(self, reference_actor, actor, distance, comparison_operator=operator.lt,
distance_type="cartesianDistance", freespace=False, name="TriggerDistanceToVehicle"):
"""
Setup trigger distance
"""
super(InTriggerDistanceToVehicle, self).__init__(name)
self.logger.debug("%s.__init__()" % (self.__class__.__name__))
self._reference_actor = reference_actor
self._actor = actor
self._distance = distance
self._distance_type = distance_type
self._freespace = freespace
self._comparison_operator = comparison_operator
if distance_type == "longitudinal":
self._global_rp = CarlaDataProvider.get_global_route_planner()
else:
self._global_rp = None
def update(self):
"""
Check if the ego vehicle is within trigger distance to other actor
"""
new_status = py_trees.common.Status.RUNNING
location = CarlaDataProvider.get_location(self._actor)
reference_location = CarlaDataProvider.get_location(self._reference_actor)
if location is None or reference_location is None:
return new_status
distance = get_distance_between_actors(
self._actor, self._reference_actor, self._distance_type, self._freespace, self._global_rp)
if self._comparison_operator(distance, self._distance):
new_status = py_trees.common.Status.SUCCESS
self.logger.debug("%s.update()[%s->%s]" % (self.__class__.__name__, self.status, new_status))
return new_status
class InTriggerDistanceToLocation(AtomicCondition):
"""
This class contains the trigger (condition) for a distance to a fixed
location of a scenario
Important parameters:
- actor: CARLA actor to execute the behavior
- target_location: Reference location (carla.location)
- name: Name of the condition
- distance: Trigger distance between the actor and the target location in meters
The condition terminates with SUCCESS, when the actor reached the target distance to the given location
"""
def __init__(self,
actor,
target_location,
distance,
comparison_operator=operator.lt,
name="InTriggerDistanceToLocation"):
"""
Setup trigger distance
"""
super(InTriggerDistanceToLocation, self).__init__(name)
self.logger.debug("%s.__init__()" % (self.__class__.__name__))
self._target_location = target_location
self._actor = actor
self._distance = distance
self._comparison_operator = comparison_operator
def update(self):
"""
Check if the actor is within trigger distance to the target location
"""
new_status = py_trees.common.Status.RUNNING
location = CarlaDataProvider.get_location(self._actor)
if location is None:
return new_status
if self._comparison_operator(calculate_distance(
location, self._target_location), self._distance):
new_status = py_trees.common.Status.SUCCESS
self.logger.debug("%s.update()[%s->%s]" % (self.__class__.__name__, self.status, new_status))
return new_status
class InTriggerDistanceToNextIntersection(AtomicCondition):
"""
This class contains the trigger (condition) for a distance to the
next intersection of a scenario
Important parameters:
- actor: CARLA actor to execute the behavior
- name: Name of the condition
- distance: Trigger distance between the actor and the next intersection in meters
The condition terminates with SUCCESS, when the actor reached the target distance to the next intersection
"""
def __init__(self, actor, distance, name="InTriggerDistanceToNextIntersection"):
"""
Setup trigger distance
"""
super(InTriggerDistanceToNextIntersection, self).__init__(name)
self.logger.debug("%s.__init__()" % (self.__class__.__name__))
self._actor = actor
self._distance = distance
self._map = CarlaDataProvider.get_map()
waypoint = self._map.get_waypoint(self._actor.get_location())
while waypoint and not waypoint.is_junction:
waypoint = waypoint.next(1)[-1]
self._final_location = waypoint.transform.location
def update(self):
"""
Check if the actor is within trigger distance to the intersection
"""
new_status = py_trees.common.Status.RUNNING
current_waypoint = self._map.get_waypoint(CarlaDataProvider.get_location(self._actor))
distance = calculate_distance(current_waypoint.transform.location, self._final_location)
if distance < self._distance:
new_status = py_trees.common.Status.SUCCESS
self.logger.debug("%s.update()[%s->%s]" % (self.__class__.__name__, self.status, new_status))
return new_status
class InTriggerDistanceToLocationAlongRoute(AtomicCondition):
"""
Implementation for a behavior that will check if a given actor
is within a given distance to a given location considering a given route
Important parameters:
- actor: CARLA actor to execute the behavior
- name: Name of the condition
- distance: Trigger distance between the actor and the next intersection in meters
- route: Route to be checked
- location: Location on the route to be checked
The condition terminates with SUCCESS, when the actor reached the target distance
along its route to the given location
"""
def __init__(self, actor, route, location, distance, name="InTriggerDistanceToLocationAlongRoute"):
"""
Setup class members
"""
super(InTriggerDistanceToLocationAlongRoute, self).__init__(name)
self._map = CarlaDataProvider.get_map()
self._actor = actor
self._location = location
self._route = route
self._distance = distance
self._location_distance, _ = get_distance_along_route(self._route, self._location)
def update(self):
new_status = py_trees.common.Status.RUNNING
current_location = CarlaDataProvider.get_location(self._actor)
if current_location is None:
return new_status
if current_location.distance(self._location) < self._distance + 20:
actor_distance, _ = get_distance_along_route(self._route, current_location)
# If closer than self._distance and hasn't passed the trigger point
if (self._location_distance < actor_distance + self._distance and
actor_distance < self._location_distance) or \
self._location_distance < 1.0:
new_status = py_trees.common.Status.SUCCESS
return new_status
class InTimeToArrivalToLocation(AtomicCondition):
"""
This class contains a check if a actor arrives within a given time
at a given location.
Important parameters:
- actor: CARLA actor to execute the behavior
- name: Name of the condition
- time: The behavior is successful, if TTA is less than _time_ in seconds
- location: Location to be checked in this behavior
The condition terminates with SUCCESS, when the actor can reach the target location within the given time
"""
_max_time_to_arrival = float('inf') # time to arrival in seconds
def __init__(self, actor, time, location, comparison_operator=operator.lt, name="TimeToArrival"):
"""
Setup parameters
"""
super(InTimeToArrivalToLocation, self).__init__(name)
self.logger.debug("%s.__init__()" % (self.__class__.__name__))
self._actor = actor
self._time = time
self._target_location = location
self._comparison_operator = comparison_operator
def update(self):
"""
Check if the actor can arrive at target_location within time
"""
new_status = py_trees.common.Status.RUNNING
current_location = CarlaDataProvider.get_location(self._actor)
if current_location is None:
return new_status
distance = calculate_distance(current_location, self._target_location)
velocity = CarlaDataProvider.get_velocity(self._actor)
# if velocity is too small, simply use a large time to arrival
time_to_arrival = self._max_time_to_arrival
if velocity > EPSILON:
time_to_arrival = distance / velocity
if self._comparison_operator(time_to_arrival, self._time):
new_status = py_trees.common.Status.SUCCESS
self.logger.debug("%s.update()[%s->%s]" % (self.__class__.__name__, self.status, new_status))
return new_status
class InTimeToArrivalToVehicle(AtomicCondition):
"""
This class contains a check if a actor arrives within a given time
at another actor.
Important parameters:
- actor: CARLA actor to execute the behavior
- name: Name of the condition
- time: The behavior is successful, if TTA is less than _time_ in seconds
- other_actor: Reference actor used in this behavior
The condition terminates with SUCCESS, when the actor can reach the other vehicle within the given time
"""
_max_time_to_arrival = float('inf') # time to arrival in seconds
def __init__(self, actor, other_actor, time, condition_freespace=False,
along_route=False, comparison_operator=operator.lt, name="TimeToArrival"):
"""
Setup parameters
"""
super(InTimeToArrivalToVehicle, self).__init__(name)
self.logger.debug("%s.__init__()" % (self.__class__.__name__))
self._map = CarlaDataProvider.get_map()
self._actor = actor
self._other_actor = other_actor
self._time = time
self._condition_freespace = condition_freespace
self._along_route = along_route
self._comparison_operator = comparison_operator
if self._along_route:
# Get the global route planner, used to calculate the route
self._grp = GlobalRoutePlanner(self._map, 0.5)
else:
self._grp = None
def update(self):
"""
Check if the ego vehicle can arrive at other actor within time
"""
new_status = py_trees.common.Status.RUNNING
current_location = CarlaDataProvider.get_location(self._actor)
other_location = CarlaDataProvider.get_location(self._other_actor)
# Get the bounding boxes
if self._condition_freespace:
if isinstance(self._actor, (carla.Vehicle, carla.Walker)):
actor_extent = self._actor.bounding_box.extent.x
else:
# Patch, as currently static objects have no bounding boxes
actor_extent = 0
if isinstance(self._other_actor, (carla.Vehicle, carla.Walker)):
other_extent = self._other_actor.bounding_box.extent.x
else:
# Patch, as currently static objects have no bounding boxes
other_extent = 0
if current_location is None or other_location is None:
return new_status
current_velocity = CarlaDataProvider.get_velocity(self._actor)
other_velocity = CarlaDataProvider.get_velocity(self._other_actor)
if self._along_route:
# Global planner needs a location at a driving lane
current_location = self._map.get_waypoint(current_location).transform.location
other_location = self._map.get_waypoint(other_location).transform.location
distance = calculate_distance(current_location, other_location, self._grp)
# if velocity is too small, simply use a large time to arrival
time_to_arrival = self._max_time_to_arrival
if current_velocity > other_velocity:
if self._condition_freespace:
time_to_arrival = (distance - actor_extent - other_extent) / (current_velocity - other_velocity)
else:
time_to_arrival = distance / (current_velocity - other_velocity)
if self._comparison_operator(time_to_arrival, self._time):
new_status = py_trees.common.Status.SUCCESS
self.logger.debug("%s.update()[%s->%s]" % (self.__class__.__name__, self.status, new_status))
return new_status
class InTimeToArrivalToVehicleSideLane(InTimeToArrivalToLocation):
"""
This class contains a check if a actor arrives within a given time
at another actor's side lane. Inherits from InTimeToArrivalToLocation
Important parameters:
- actor: CARLA actor to execute the behavior
- name: Name of the condition
- time: The behavior is successful, if TTA is less than _time_ in seconds