-
Notifications
You must be signed in to change notification settings - Fork 372
/
Copy pathatomic_criteria.py
2196 lines (1715 loc) · 85.8 KB
/
atomic_criteria.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 evaluation criteria required to analyze if a
scenario was completed successfully or failed.
Criteria should run continuously to monitor the state of a single actor, multiple
actors or environmental parameters. Hence, a termination is not required.
The atomic criteria are implemented with py_trees.
"""
import math
import numpy as np
import py_trees
import shapely.geometry
import carla
from agents.tools.misc import get_speed
from srunner.scenariomanager.carla_data_provider import CarlaDataProvider
from srunner.scenariomanager.timer import GameTime
from srunner.scenariomanager.traffic_events import TrafficEvent, TrafficEventType
class Criterion(py_trees.behaviour.Behaviour):
"""
Base class for all criteria used to evaluate a scenario for success/failure
Important parameters (PUBLIC):
- name: Name of the criterion
- actor: Actor of the criterion
- optional: Indicates if a criterion is optional (not used for overall analysis)
- terminate on failure: Whether or not the criteria stops on failure
- test_status: Used to access the result of the criterion
- success_value: Result in case of success (e.g. max_speed, zero collisions, ...)
- acceptable_value: Result that does not mean a failure, but is not good enough for a success
- actual_value: Actual result after running the scenario
- units: units of the 'actual_value'. This is a string and is used by the result writter
"""
def __init__(self,
name,
actor,
optional=False,
terminate_on_failure=False):
super(Criterion, self).__init__(name)
self.logger.debug("%s.__init__()" % (self.__class__.__name__))
self.name = name
self.actor = actor
self.optional = optional
self._terminate_on_failure = terminate_on_failure
self.test_status = "INIT" # Either "INIT", "RUNNING", "SUCCESS", "ACCEPTABLE" or "FAILURE"
# Attributes to compare the current state (actual_value), with the expected ones
self.success_value = 0
self.acceptable_value = None
self.actual_value = 0
self.units = "times"
self.events = [] # List of events (i.e collision, sidewalk invasion...)
def initialise(self):
"""
Initialise the criterion. Can be extended by the user-derived class
"""
self.logger.debug("%s.initialise()" % (self.__class__.__name__))
def terminate(self, new_status):
"""
Terminate the criterion. Can be extended by the user-derived class
"""
if self.test_status in ('RUNNING', 'INIT'):
self.test_status = "SUCCESS"
self.logger.debug("%s.terminate()[%s->%s]" % (self.__class__.__name__, self.status, new_status))
class MaxVelocityTest(Criterion):
"""
This class contains an atomic test for maximum velocity.
Important parameters:
- actor: CARLA actor to be used for this test
- max_velocity_allowed: maximum allowed velocity in m/s
- optional [optional]: If True, the result is not considered for an overall pass/fail result
"""
def __init__(self, actor, max_velocity, optional=False, name="CheckMaximumVelocity"):
"""
Setup actor and maximum allowed velovity
"""
super(MaxVelocityTest, self).__init__(name, actor, optional)
self.success_value = max_velocity
def update(self):
"""
Check velocity
"""
new_status = py_trees.common.Status.RUNNING
if self.actor is None:
return new_status
velocity = CarlaDataProvider.get_velocity(self.actor)
self.actual_value = max(velocity, self.actual_value)
if velocity > self.success_value:
self.test_status = "FAILURE"
else:
self.test_status = "SUCCESS"
if self._terminate_on_failure and (self.test_status == "FAILURE"):
new_status = py_trees.common.Status.FAILURE
self.logger.debug("%s.update()[%s->%s]" % (self.__class__.__name__, self.status, new_status))
return new_status
class DrivenDistanceTest(Criterion):
"""
This class contains an atomic test to check the driven distance
Important parameters:
- actor: CARLA actor to be used for this test
- distance_success: If the actor's driven distance is more than this value (in meters),
the test result is SUCCESS
- distance_acceptable: If the actor's driven distance is more than this value (in meters),
the test result is ACCEPTABLE
- optional [optional]: If True, the result is not considered for an overall pass/fail result
"""
def __init__(self, actor, distance, acceptable_distance=None, optional=False, name="CheckDrivenDistance"):
"""
Setup actor
"""
super(DrivenDistanceTest, self).__init__(name, actor, optional)
self.success_value = distance
self.acceptable_value = acceptable_distance
self._last_location = None
def initialise(self):
self._last_location = CarlaDataProvider.get_location(self.actor)
super(DrivenDistanceTest, self).initialise()
def update(self):
"""
Check distance
"""
new_status = py_trees.common.Status.RUNNING
if self.actor is None:
return new_status
location = CarlaDataProvider.get_location(self.actor)
if location is None:
return new_status
if self._last_location is None:
self._last_location = location
return new_status
self.actual_value += location.distance(self._last_location)
self._last_location = location
if self.actual_value > self.success_value:
self.test_status = "SUCCESS"
elif (self.acceptable_value is not None and
self.actual_value > self.acceptable_value):
self.test_status = "ACCEPTABLE"
else:
self.test_status = "RUNNING"
if self._terminate_on_failure and (self.test_status == "FAILURE"):
new_status = py_trees.common.Status.FAILURE
self.logger.debug("%s.update()[%s->%s]" % (self.__class__.__name__, self.status, new_status))
return new_status
def terminate(self, new_status):
"""
Set final status
"""
if self.test_status != "SUCCESS":
self.test_status = "FAILURE"
self.actual_value = round(self.actual_value, 2)
super(DrivenDistanceTest, self).terminate(new_status)
class AverageVelocityTest(Criterion):
"""
This class contains an atomic test for average velocity.
Important parameters:
- actor: CARLA actor to be used for this test
- avg_velocity_success: If the actor's average velocity is more than this value (in m/s),
the test result is SUCCESS
- avg_velocity_acceptable: If the actor's average velocity is more than this value (in m/s),
the test result is ACCEPTABLE
- optional [optional]: If True, the result is not considered for an overall pass/fail result
"""
def __init__(self, actor, velocity, acceptable_velocity=None, optional=False,
name="CheckAverageVelocity"):
"""
Setup actor and average velovity expected
"""
super(AverageVelocityTest, self).__init__(name, actor, optional)
self.success_value = velocity
self.acceptable_value = acceptable_velocity
self._last_location = None
self._distance = 0.0
def initialise(self):
self._last_location = CarlaDataProvider.get_location(self.actor)
super(AverageVelocityTest, self).initialise()
def update(self):
"""
Check velocity
"""
new_status = py_trees.common.Status.RUNNING
if self.actor is None:
return new_status
location = CarlaDataProvider.get_location(self.actor)
if location is None:
return new_status
if self._last_location is None:
self._last_location = location
return new_status
self._distance += location.distance(self._last_location)
self._last_location = location
elapsed_time = GameTime.get_time()
if elapsed_time > 0.0:
self.actual_value = self._distance / elapsed_time
if self.actual_value > self.success_value:
self.test_status = "SUCCESS"
elif (self.acceptable_value is not None and
self.actual_value > self.acceptable_value):
self.test_status = "ACCEPTABLE"
else:
self.test_status = "RUNNING"
if self._terminate_on_failure and (self.test_status == "FAILURE"):
new_status = py_trees.common.Status.FAILURE
self.logger.debug("%s.update()[%s->%s]" % (self.__class__.__name__, self.status, new_status))
return new_status
def terminate(self, new_status):
"""
Set final status
"""
if self.test_status == "RUNNING":
self.test_status = "FAILURE"
super(AverageVelocityTest, self).terminate(new_status)
class CollisionTest(Criterion):
"""
This class contains an atomic test for collisions.
Args:
- actor (carla.Actor): CARLA actor to be used for this test
- other_actor (carla.Actor): only collisions with this actor will be registered
- other_actor_type (str): only collisions with actors including this type_id will count.
Additionally, the "miscellaneous" tag can also be used to include all static objects in the scene
- terminate_on_failure [optional]: If True, the complete scenario will terminate upon failure of this test
- optional [optional]: If True, the result is not considered for an overall pass/fail result
"""
COLLISION_RADIUS = 5 # Two collisions that happen within this distance count as one
MAX_ID_TIME = 5 # Two collisions with the same id that happen within this time count as one
EPSILON = 0.1 # Collisions at lower this speed won't be counted as the actor's fault
def __init__(self, actor, other_actor=None, other_actor_type=None,
optional=False, terminate_on_failure=False, name="CollisionTest"):
"""
Construction with sensor setup
"""
super(CollisionTest, self).__init__(name, actor, optional, terminate_on_failure)
self.logger.debug("%s.__init__()" % (self.__class__.__name__))
self._other_actor = other_actor
self._other_actor_type = other_actor_type
# Attributes to store the last collisions's data
self._collision_sensor = None
self._collision_id = None
self._collision_time = None
self._collision_location = None
def initialise(self):
"""
Creates the sensor and callback"""
world = CarlaDataProvider.get_world()
blueprint = world.get_blueprint_library().find('sensor.other.collision')
self._collision_sensor = world.spawn_actor(blueprint, carla.Transform(), attach_to=self.actor)
self._collision_sensor.listen(lambda event: self._count_collisions(event))
super(CollisionTest, self).initialise()
def update(self):
"""
Check collision count
"""
new_status = py_trees.common.Status.RUNNING
if self._terminate_on_failure and (self.test_status == "FAILURE"):
new_status = py_trees.common.Status.FAILURE
actor_location = CarlaDataProvider.get_location(self.actor)
# Check if the last collision can be ignored
if self._collision_location:
distance_vector = actor_location - self._collision_location
if distance_vector.length() > self.COLLISION_RADIUS:
self._collision_location = None
if self._collision_id:
elapsed_time = GameTime.get_time() - self._collision_time
if elapsed_time > self.MAX_ID_TIME:
self._collision_id = None
self.logger.debug("%s.update()[%s->%s]" % (self.__class__.__name__, self.status, new_status))
return new_status
def terminate(self, new_status):
"""
Cleanup sensor
"""
if self._collision_sensor is not None:
self._collision_sensor.stop()
self._collision_sensor.destroy()
self._collision_sensor = None
super(CollisionTest, self).terminate(new_status)
def _count_collisions(self, event): # pylint: disable=too-many-return-statements
"""Update collision count"""
actor_location = CarlaDataProvider.get_location(self.actor)
# Check if the care about the other actor
if self._other_actor and self._other_actor.id != event.other_actor.id:
return
if self._other_actor_type:
if self._other_actor_type == "miscellaneous": # Special OpenScenario case
if "traffic" not in event.other_actor.type_id and "static" not in event.other_actor.type_id:
return
elif self._other_actor_type not in event.other_actor.type_id:
return
# To avoid multiple counts of the same collision, filter some of them.
if self._collision_id == event.other_actor.id:
return
if self._collision_location:
distance_vector = actor_location - self._collision_location
if distance_vector.length() <= self.COLLISION_RADIUS:
return
# If the actor speed is 0, the collision isn't its fault
if CarlaDataProvider.get_velocity(self.actor) < self.EPSILON:
return
# The collision is valid, save the data
self.test_status = "FAILURE"
self.actual_value += 1
self._collision_time = GameTime.get_time()
self._collision_location = actor_location
if event.other_actor.id != 0: # Number 0: static objects -> ignore it
self._collision_id = event.other_actor.id
if ('static' in event.other_actor.type_id or 'traffic' in event.other_actor.type_id) \
and 'sidewalk' not in event.other_actor.type_id:
actor_type = TrafficEventType.COLLISION_STATIC
elif 'vehicle' in event.other_actor.type_id:
actor_type = TrafficEventType.COLLISION_VEHICLE
elif 'walker' in event.other_actor.type_id:
actor_type = TrafficEventType.COLLISION_PEDESTRIAN
else:
return
collision_event = TrafficEvent(event_type=actor_type, frame=GameTime.get_frame())
collision_event.set_dict({'other_actor': event.other_actor, 'location': actor_location})
collision_event.set_message(
"Agent collided against object with type={} and id={} at (x={}, y={}, z={})".format(
event.other_actor.type_id,
event.other_actor.id,
round(actor_location.x, 3),
round(actor_location.y, 3),
round(actor_location.z, 3)))
self.events.append(collision_event)
class ActorBlockedTest(Criterion):
"""
This test will fail if the actor has had its linear velocity lower than a specific value for
a specific amount of time
Important parameters:
- actor: CARLA actor to be used for this test
- min_speed: speed required [m/s]
- max_time: Maximum time (in seconds) the actor can remain under the speed threshold
- terminate_on_failure [optional]: If True, the complete scenario will terminate upon failure of this test
"""
def __init__(self, actor, min_speed, max_time, name="ActorBlockedTest", optional=False, terminate_on_failure=False):
"""
Class constructor
"""
super().__init__(name, actor, optional, terminate_on_failure)
self._min_speed = min_speed
self._max_time = max_time
self._time_last_valid_state = None
self._active = True
self.units = None # We care about whether or not it fails, no units attached
def update(self):
"""
Check if the actor speed is above the min_speed
"""
new_status = py_trees.common.Status.RUNNING
# Deactivate/Activate checking by blackboard message
active = py_trees.blackboard.Blackboard().get('AC_SwitchActorBlockedTest')
if active is not None:
self._active = active
self._time_last_valid_state = GameTime.get_time()
py_trees.blackboard.Blackboard().set("AC_SwitchActorBlockedTest", None, overwrite=True)
if self._active:
linear_speed = CarlaDataProvider.get_velocity(self.actor)
if linear_speed is not None:
if linear_speed < self._min_speed and self._time_last_valid_state:
if (GameTime.get_time() - self._time_last_valid_state) > self._max_time:
# The actor has been "blocked" for too long, save the data
self.test_status = "FAILURE"
vehicle_location = CarlaDataProvider.get_location(self.actor)
event = TrafficEvent(event_type=TrafficEventType.VEHICLE_BLOCKED, frame=GameTime.get_frame())
event.set_message('Agent got blocked at (x={}, y={}, z={})'.format(
round(vehicle_location.x, 3),
round(vehicle_location.y, 3),
round(vehicle_location.z, 3))
)
event.set_dict({'location': vehicle_location})
self.events.append(event)
else:
self._time_last_valid_state = GameTime.get_time()
if self._terminate_on_failure and (self.test_status == "FAILURE"):
new_status = py_trees.common.Status.FAILURE
self.logger.debug("%s.update()[%s->%s]" % (self.__class__.__name__, self.status, new_status))
return new_status
class KeepLaneTest(Criterion):
"""
This class contains an atomic test for keeping lane.
Important parameters:
- actor: CARLA actor to be used for this test
- optional [optional]: If True, the result is not considered for an overall pass/fail result
"""
def __init__(self, actor, optional=False, name="CheckKeepLane"):
"""
Construction with sensor setup
"""
super(KeepLaneTest, self).__init__(name, actor, optional)
world = self.actor.get_world()
blueprint = world.get_blueprint_library().find('sensor.other.lane_invasion')
self._lane_sensor = world.spawn_actor(blueprint, carla.Transform(), attach_to=self.actor)
self._lane_sensor.listen(lambda event: self._count_lane_invasion(event))
def update(self):
"""
Check lane invasion count
"""
new_status = py_trees.common.Status.RUNNING
if self.actual_value > 0:
self.test_status = "FAILURE"
else:
self.test_status = "SUCCESS"
if self._terminate_on_failure and (self.test_status == "FAILURE"):
new_status = py_trees.common.Status.FAILURE
self.logger.debug("%s.update()[%s->%s]" % (self.__class__.__name__, self.status, new_status))
return new_status
def terminate(self, new_status):
"""
Cleanup sensor
"""
if self._lane_sensor is not None:
self._lane_sensor.destroy()
self._lane_sensor = None
super(KeepLaneTest, self).terminate(new_status)
def _count_lane_invasion(self, event):
"""
Callback to update lane invasion count
"""
self.actual_value += 1
class ReachedRegionTest(Criterion):
"""
This class contains the reached region test
The test is a success if the actor reaches a specified region
Important parameters:
- actor: CARLA actor to be used for this test
- min_x, max_x, min_y, max_y: Bounding box of the checked region
"""
def __init__(self, actor, min_x, max_x, min_y, max_y, name="ReachedRegionTest"):
"""
Setup trigger region (rectangle provided by
[min_x,min_y] and [max_x,max_y]
"""
super(ReachedRegionTest, self).__init__(name, 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
in_region = False
if self.test_status != "SUCCESS":
in_region = (location.x > self._min_x and location.x < self._max_x) and (
location.y > self._min_y and location.y < self._max_y)
if in_region:
self.test_status = "SUCCESS"
else:
self.test_status = "RUNNING"
if self.test_status == "SUCCESS":
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 OffRoadTest(Criterion):
"""
Atomic containing a test to detect when an actor deviates from the driving lanes. This atomic can
fail when actor has spent a specific time outside driving lanes (defined by OpenDRIVE). Simplified
version of OnSidewalkTest, and doesn't relly on waypoints with *Sidewalk* lane types
Args:
actor (carla.Actor): CARLA actor to be used for this test
duration (float): Time spent at sidewalks before the atomic fails.
If terminate_on_failure isn't active, this is ignored.
optional (bool): If True, the result is not considered for an overall pass/fail result
when using the output argument
terminate_on_failure (bool): If True, the atomic will fail when the duration condition has been met.
"""
def __init__(self, actor, duration=0, optional=False, terminate_on_failure=False, name="OffRoadTest"):
"""
Setup of the variables
"""
super(OffRoadTest, self).__init__(name, actor, optional, terminate_on_failure)
self._map = CarlaDataProvider.get_map()
self._offroad = False
self._duration = duration
self._prev_time = None
self._time_offroad = 0
def update(self):
"""
First, transforms the actor's current position to its corresponding waypoint. This is
filtered to only use waypoints of type Driving or Parking. Depending on these results,
the actor will be considered to be outside (or inside) driving lanes.
returns:
py_trees.common.Status.FAILURE: when the actor has spent a given duration outside driving lanes
py_trees.common.Status.RUNNING: the rest of the time
"""
new_status = py_trees.common.Status.RUNNING
current_location = CarlaDataProvider.get_location(self.actor)
# Get the waypoint at the current location to see if the actor is offroad
drive_waypoint = self._map.get_waypoint(
current_location,
project_to_road=False
)
park_waypoint = self._map.get_waypoint(
current_location,
project_to_road=False,
lane_type=carla.LaneType.Parking
)
if drive_waypoint or park_waypoint:
self._offroad = False
else:
self._offroad = True
# Counts the time offroad
if self._offroad:
if self._prev_time is None:
self._prev_time = GameTime.get_time()
else:
curr_time = GameTime.get_time()
self._time_offroad += curr_time - self._prev_time
self._prev_time = curr_time
else:
self._prev_time = None
if self._time_offroad > self._duration:
self.test_status = "FAILURE"
if self._terminate_on_failure and self.test_status == "FAILURE":
new_status = py_trees.common.Status.FAILURE
self.logger.debug("%s.update()[%s->%s]" % (self.__class__.__name__, self.status, new_status))
return new_status
class EndofRoadTest(Criterion):
"""
Atomic containing a test to detect when an actor has changed to a different road
Args:
actor (carla.Actor): CARLA actor to be used for this test
duration (float): Time spent after ending the road before the atomic fails.
If terminate_on_failure isn't active, this is ignored.
optional (bool): If True, the result is not considered for an overall pass/fail result
when using the output argument
terminate_on_failure (bool): If True, the atomic will fail when the duration condition has been met.
"""
def __init__(self, actor, duration=0, optional=False, terminate_on_failure=False, name="EndofRoadTest"):
"""
Setup of the variables
"""
super(EndofRoadTest, self).__init__(name, actor, optional, terminate_on_failure)
self._map = CarlaDataProvider.get_map()
self._end_of_road = False
self._duration = duration
self._start_time = None
self._time_end_road = 0
self._road_id = None
def update(self):
"""
First, transforms the actor's current position to its corresponding waypoint. Then the road id
is compared with the initial one and if that's the case, a time is started
returns:
py_trees.common.Status.FAILURE: when the actor has spent a given duration outside driving lanes
py_trees.common.Status.RUNNING: the rest of the time
"""
new_status = py_trees.common.Status.RUNNING
current_location = CarlaDataProvider.get_location(self.actor)
current_waypoint = self._map.get_waypoint(current_location)
# Get the current road id
if self._road_id is None:
self._road_id = current_waypoint.road_id
else:
# Wait until the actor has left the road
if self._road_id != current_waypoint.road_id or self._start_time:
# Start counting
if self._start_time is None:
self._start_time = GameTime.get_time()
return new_status
curr_time = GameTime.get_time()
self._time_end_road = curr_time - self._start_time
if self._time_end_road > self._duration:
self.test_status = "FAILURE"
self.actual_value += 1
return py_trees.common.Status.SUCCESS
self.logger.debug("%s.update()[%s->%s]" % (self.__class__.__name__, self.status, new_status))
return new_status
class OnSidewalkTest(Criterion):
"""
Atomic containing a test to detect sidewalk invasions of a specific actor. This atomic can
fail when actor has spent a specific time outside driving lanes (defined by OpenDRIVE).
Args:
actor (carla.Actor): CARLA actor to be used for this test
duration (float): Time spent at sidewalks before the atomic fails.
If terminate_on_failure isn't active, this is ignored.
optional (bool): If True, the result is not considered for an overall pass/fail result
when using the output argument
terminate_on_failure (bool): If True, the atomic will fail when the duration condition has been met.
"""
def __init__(self, actor, duration=0, optional=False, terminate_on_failure=False, name="OnSidewalkTest"):
"""
Construction with sensor setup
"""
super(OnSidewalkTest, self).__init__(name, actor, optional, terminate_on_failure)
self._map = CarlaDataProvider.get_map()
self._onsidewalk_active = False
self._outside_lane_active = False
self._actor_location = self.actor.get_location()
self._wrong_sidewalk_distance = 0
self._wrong_outside_lane_distance = 0
self._sidewalk_start_location = None
self._outside_lane_start_location = None
self._duration = duration
self._prev_time = None
self._time_outside_lanes = 0
def update(self):
"""
First, transforms the actor's current position as well as its four corners to their
corresponding waypoints. Depending on their lane type, the actor will be considered to be
outside (or inside) driving lanes.
returns:
py_trees.common.Status.FAILURE: when the actor has spent a given duration outside
driving lanes and terminate_on_failure is active
py_trees.common.Status.RUNNING: the rest of the time
"""
new_status = py_trees.common.Status.RUNNING
if self._terminate_on_failure and self.test_status == "FAILURE":
new_status = py_trees.common.Status.FAILURE
# Some of the vehicle parameters
current_tra = CarlaDataProvider.get_transform(self.actor)
current_loc = current_tra.location
current_wp = self._map.get_waypoint(current_loc, lane_type=carla.LaneType.Any)
# Case 1) Car center is at a sidewalk
if current_wp.lane_type == carla.LaneType.Sidewalk:
if not self._onsidewalk_active:
self._onsidewalk_active = True
self._sidewalk_start_location = current_loc
# Case 2) Not inside allowed zones (Driving and Parking)
elif current_wp.lane_type not in (carla.LaneType.Driving, carla.LaneType.Parking):
# Get the vertices of the vehicle
heading_vec = current_tra.get_forward_vector()
heading_vec.z = 0
heading_vec = heading_vec / math.sqrt(math.pow(heading_vec.x, 2) + math.pow(heading_vec.y, 2))
perpendicular_vec = carla.Vector3D(-heading_vec.y, heading_vec.x, 0)
extent = self.actor.bounding_box.extent
x_boundary_vector = heading_vec * extent.x
y_boundary_vector = perpendicular_vec * extent.y
bbox = [
current_loc + carla.Location(x_boundary_vector - y_boundary_vector),
current_loc + carla.Location(x_boundary_vector + y_boundary_vector),
current_loc + carla.Location(-1 * x_boundary_vector - y_boundary_vector),
current_loc + carla.Location(-1 * x_boundary_vector + y_boundary_vector)]
bbox_wp = [
self._map.get_waypoint(bbox[0], lane_type=carla.LaneType.Any),
self._map.get_waypoint(bbox[1], lane_type=carla.LaneType.Any),
self._map.get_waypoint(bbox[2], lane_type=carla.LaneType.Any),
self._map.get_waypoint(bbox[3], lane_type=carla.LaneType.Any)]
lane_type_list = [bbox_wp[0].lane_type, bbox_wp[1].lane_type, bbox_wp[2].lane_type, bbox_wp[3].lane_type]
# Case 2.1) Not quite outside yet
if bbox_wp[0].lane_type == (carla.LaneType.Driving or carla.LaneType.Parking) \
or bbox_wp[1].lane_type == (carla.LaneType.Driving or carla.LaneType.Parking) \
or bbox_wp[2].lane_type == (carla.LaneType.Driving or carla.LaneType.Parking) \
or bbox_wp[3].lane_type == (carla.LaneType.Driving or carla.LaneType.Parking):
self._onsidewalk_active = False
self._outside_lane_active = False
# Case 2.2) At the mini Shoulders between Driving and Sidewalk
elif carla.LaneType.Sidewalk in lane_type_list:
if not self._onsidewalk_active:
self._onsidewalk_active = True
self._sidewalk_start_location = current_loc
else:
distance_vehicle_wp = current_loc.distance(current_wp.transform.location)
# Case 2.3) Outside lane
if distance_vehicle_wp >= current_wp.lane_width / 2:
if not self._outside_lane_active:
self._outside_lane_active = True
self._outside_lane_start_location = current_loc
# Case 2.4) Very very edge case (but still inside driving lanes)
else:
self._onsidewalk_active = False
self._outside_lane_active = False
# Case 3) Driving and Parking conditions
else:
# Check for false positives at junctions
if current_wp.is_junction:
distance_vehicle_wp = math.sqrt(
math.pow(current_wp.transform.location.x - current_loc.x, 2) +
math.pow(current_wp.transform.location.y - current_loc.y, 2))
if distance_vehicle_wp <= current_wp.lane_width / 2:
self._onsidewalk_active = False
self._outside_lane_active = False
# Else, do nothing, the waypoint is too far to consider it a correct position
else:
self._onsidewalk_active = False
self._outside_lane_active = False
# Counts the time offroad
if self._onsidewalk_active or self._outside_lane_active:
if self._prev_time is None:
self._prev_time = GameTime.get_time()
else:
curr_time = GameTime.get_time()
self._time_outside_lanes += curr_time - self._prev_time
self._prev_time = curr_time
else:
self._prev_time = None
if self._time_outside_lanes > self._duration:
self.test_status = "FAILURE"
# Update the distances
distance_vector = CarlaDataProvider.get_location(self.actor) - self._actor_location
distance = math.sqrt(math.pow(distance_vector.x, 2) + math.pow(distance_vector.y, 2))
if distance >= 0.02: # Used to avoid micro-changes adding to considerable sums
self._actor_location = CarlaDataProvider.get_location(self.actor)
if self._onsidewalk_active:
self._wrong_sidewalk_distance += distance
elif self._outside_lane_active:
# Only add if car is outside the lane but ISN'T in a junction
self._wrong_outside_lane_distance += distance
# Register the sidewalk event
if not self._onsidewalk_active and self._wrong_sidewalk_distance > 0:
self.actual_value += 1
onsidewalk_event = TrafficEvent(event_type=TrafficEventType.ON_SIDEWALK_INFRACTION, frame=GameTime.get_frame())
self._set_event_message(
onsidewalk_event, self._sidewalk_start_location, self._wrong_sidewalk_distance)
self._set_event_dict(
onsidewalk_event, self._sidewalk_start_location, self._wrong_sidewalk_distance)
self._onsidewalk_active = False
self._wrong_sidewalk_distance = 0
self.events.append(onsidewalk_event)
# Register the outside of a lane event
if not self._outside_lane_active and self._wrong_outside_lane_distance > 0:
self.actual_value += 1
outsidelane_event = TrafficEvent(event_type=TrafficEventType.OUTSIDE_LANE_INFRACTION, frame=GameTime.get_frame())
self._set_event_message(
outsidelane_event, self._outside_lane_start_location, self._wrong_outside_lane_distance)
self._set_event_dict(
outsidelane_event, self._outside_lane_start_location, self._wrong_outside_lane_distance)
self._outside_lane_active = False
self._wrong_outside_lane_distance = 0
self.events.append(outsidelane_event)
self.logger.debug("%s.update()[%s->%s]" % (self.__class__.__name__, self.status, new_status))
return new_status
def terminate(self, new_status):
"""
If there is currently an event running, it is registered
"""
# If currently at a sidewalk, register the event
if self._onsidewalk_active:
self.actual_value += 1
onsidewalk_event = TrafficEvent(event_type=TrafficEventType.ON_SIDEWALK_INFRACTION, frame=GameTime.get_frame())
self._set_event_message(
onsidewalk_event, self._sidewalk_start_location, self._wrong_sidewalk_distance)
self._set_event_dict(
onsidewalk_event, self._sidewalk_start_location, self._wrong_sidewalk_distance)
self._onsidewalk_active = False
self._wrong_sidewalk_distance = 0
self.events.append(onsidewalk_event)
# If currently outside of our lane, register the event
if self._outside_lane_active:
self.actual_value += 1
outsidelane_event = TrafficEvent(event_type=TrafficEventType.OUTSIDE_LANE_INFRACTION, frame=GameTime.get_frame())
self._set_event_message(
outsidelane_event, self._outside_lane_start_location, self._wrong_outside_lane_distance)
self._set_event_dict(
outsidelane_event, self._outside_lane_start_location, self._wrong_outside_lane_distance)
self._outside_lane_active = False
self._wrong_outside_lane_distance = 0
self.events.append(outsidelane_event)
super(OnSidewalkTest, self).terminate(new_status)
def _set_event_message(self, event, location, distance):
"""
Sets the message of the event
"""
if event.get_type() == TrafficEventType.ON_SIDEWALK_INFRACTION:
message_start = 'Agent invaded the sidewalk'
else:
message_start = 'Agent went outside the lane'
event.set_message(
'{} for about {} meters, starting at (x={}, y={}, z={})'.format(
message_start,
round(distance, 3),
round(location.x, 3),
round(location.y, 3),
round(location.z, 3)))
def _set_event_dict(self, event, location, distance):
"""
Sets the dictionary of the event
"""
event.set_dict({'location': location, 'distance': distance})
class OutsideRouteLanesTest(Criterion):
"""
Atomic to detect if the vehicle is either on a sidewalk or at a wrong lane. The distance spent outside
is computed and it is returned as a percentage of the route distance traveled.
Args:
actor (carla.ACtor): CARLA actor to be used for this test
route (list [carla.Location, connection]): series of locations representing the route waypoints
optional (bool): If True, the result is not considered for an overall pass/fail result
"""
ALLOWED_OUT_DISTANCE = 0.5 # At least 0.5, due to the mini-shoulder between lanes and sidewalks
MAX_VEHICLE_ANGLE = 120.0 # Maximum angle between the yaw and waypoint lane
MAX_WAYPOINT_ANGLE = 150.0 # Maximum change between the yaw-lane angle between frames
WINDOWS_SIZE = 3 # Amount of additional waypoints checked (in case the first on fails)