-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathnpz_trajectory.py
1829 lines (1629 loc) · 66 KB
/
npz_trajectory.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
import math
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from matplotlib.pyplot import figure
from mpl_toolkits.mplot3d.art3d import Poly3DCollection
import sys
from PIL import Image
import glob
from PIL import Image
class NpzTrajectory:
# print(f"Object ID: {data['object_id']}")
# print(f"Yaw: {data['yaw']}")
# print(f"Shift: {data['shift']}")
# print(f"GT Marginal: {data['_gt_marginal']}")
# print(f"GT Joint: {data['gt_joint']}")
# print(f"Shape of GT Joint: {data['gt_joint'].shape}")
# print(f"Future Val Marginal: {data['future_val_marginal']}")
# print(f"Future Val Joint: {data['future_val_joint']}")
# print(f"Scenario ID: {data['scenario_id']}")
# print(f"Self Type: {data['self_type']}")
# print(f"Vector Data: {data['vector_data']}")
def __init__(self, path):
self.path = path
self.init_data()
def init_data(self):
with np.load(self.path) as data:
self.object_id = data["object_id"]
self.raster = data["raster"]
self.yaw = data["yaw"]
self.shift = data["shift"]
self._gt_marginal = data["_gt_marginal"]
self.gt_marginal = data["gt_marginal"]
self.future_val_marginal = data["future_val_marginal"]
self.gt_joint = data["gt_joint"]
self.scenario_id = data["scenario_id"]
self.type = data["self_type"]
self.vector_data = data["vector_data"]
self.coordinates = self.get_parsed_coordinates()
self.direction = self.get_direction_of_vehicle()
self.movement_vectors = self.get_movement_vectors()
def get_parsed_coordinates(self):
# V = self.vector_data
# X, idx = V[:, :44], V[:, 44].flatten()
# for i in np.unique(idx):
# _X = X[(idx == i)]
# if _X[-1, 0] == 0 and _X[-1, 1] == 0:
# x = np.flip(_X[:, 0])
# y = np.flip(_X[:, 1])
# print(x)
x = self.gt_marginal[:, 0]
y = self.gt_marginal[:, 1]
coordinates = pd.DataFrame({"X": x, "Y": y})
return coordinates
def visualize_raw_coordinates_without_scenario(
self, coordinates, title="Trajectory Visualization", padding=10
):
"""
Visualize the trajectory specified by coordinates, scaling to fit the trajectory size.
Args:
- coordinates: A DataFrame with 'X' and 'Y' columns, or an array-like structure representing trajectory points.
- title: The title of the plot.
- padding: Extra space around the trajectory bounds.
"""
fig, ax = plt.subplots(
figsize=(10, 10)
) # Create a figure and a set of subplots
# Scale the normalized trajectory to fit the figure
# Plot the trajectory
ax.plot(
coordinates["X"],
coordinates["Y"],
"ro-",
markersize=5,
linewidth=2,
) # 'ro-' creates a red line with circle markers
# Set aspect of the plot to be equal
ax.set_aspect("equal")
# Set title of the plot
# ax.set_title(title)
# Remove axes for a cleaner look since there's no map
# ax.axis("off")
return plt
@staticmethod
def remove_outlier_angles(delta_angles: list):
"""Removes outlier angles from a list of angles.
Args:
delta_angles (list): A list of angles.
"""
filtered_delta_angles = []
for angle in delta_angles:
if angle < 20 and angle > -20:
filtered_delta_angles.append(angle)
return filtered_delta_angles
def get_movement_vectors(self):
vectors = []
x = self._gt_marginal[:, 0]
y = self._gt_marginal[:, 1]
for i in range(len(x) - 2):
current_vector = [x[i] - x[i + 1], y[i] - y[i + 1]]
vectors.append(current_vector)
return vectors
def get_delta_angles(self, coordinates: pd.DataFrame):
"""Returns the angle between each segment in the trajectory.
Args:
coordinates (pd.DataFrame): A dataframe containing the coordinates
of the vehicle trajectory.
"""
delta_angles = []
for i in range(1, len(coordinates) - 1):
# Calculate the direction vector of the current segment
current_vector = np.array(
(
coordinates.iloc[i + 1]["X"] - coordinates.iloc[i]["X"],
coordinates.iloc[i + 1]["Y"] - coordinates.iloc[i]["Y"],
)
)
# Calculate the direction vector of the previous segment
previous_vector = np.array(
(
coordinates.iloc[i]["X"] - coordinates.iloc[i - 1]["X"],
coordinates.iloc[i]["Y"] - coordinates.iloc[i - 1]["Y"],
)
)
# Compute the angle between the current and previous direction vectors
angle = self.angle_between(current_vector, previous_vector)
direction = self.get_gross_direction_for_three_points(
coordinates.iloc[i - 1], coordinates.iloc[i], coordinates.iloc[i + 1]
)
if direction == "Right":
angle = -angle
delta_angles.append(angle)
return delta_angles
def unit_vector(self, vector):
"""Returns the unit vector of the vector."""
return vector / np.linalg.norm(vector)
def angle_between(self, v1, v2):
"""Returns the angle in radians between vectors 'v1' and 'v2'::"""
v1_u = self.unit_vector(v1)
v2_u = self.unit_vector(v2)
return math.degrees(np.arccos(np.clip(np.dot(v1_u, v2_u), -1.0, 1.0)))
def get_sum_of_delta_angles(self) -> float:
"""Returns the sum of the angles between each segment in the trajectory.
Args:
coordinates (pd.DataFrame): A dataframe containing the coordinates
of the vehicle trajectory.
"""
delta_angles = self.get_delta_angles(self.coordinates)
filtered_delta_angles = self.remove_outlier_angles(delta_angles)
return sum(filtered_delta_angles)
def get_angle_between_vectors(self, v1, v2):
"""Returns the angle between two vectors.
Args:
v1 (np.array): The first vector.
v2 (np.array): The second vector.
"""
v1_length = np.linalg.norm(v1)
v2_length = np.linalg.norm(v2)
if v1_length == 0 or v2_length == 0:
return 0
product = (v1 @ v2) / (v1_length * v2_length)
if product > 1:
return 0
if product < -1:
return 180
acos = math.acos(product)
result_angle = acos * (180 / math.pi)
if result_angle > 180:
result_angle = 360 - result_angle
return result_angle
def get_direction_of_vehicle(self):
"""Sorts a given trajectory into one of the
following buckets:
- Straight
- Straight-Left
- Straight-Right
- Left
- Right
- Left-U-Turn
- Right-U-Turn
- Stationary
These buckets are inspired by the paper:
"MotionLM: Multi-Agent Motion Forecasting as Language Modeling"
Returns:
str: Label of the bucket to which the vehicle trajectory was assigned.
"""
total_delta_angle = self.get_sum_of_delta_angles()
direction = ""
bucket = ""
if total_delta_angle < 0:
direction = "Right"
elif total_delta_angle > 0:
direction = "Left"
else:
direction = "Straight"
absolute_total_delta_angle = abs(total_delta_angle)
if self.get_relative_displacement() < 0.03:
bucket = "Stationary"
return bucket
elif absolute_total_delta_angle < 15 and absolute_total_delta_angle > -15:
bucket = "Straight"
return bucket
elif absolute_total_delta_angle <= 40 and direction == "Right":
bucket = "Straight-Right"
return bucket
elif absolute_total_delta_angle <= 40 and direction == "Left":
bucket = "Straight-Left"
return bucket
elif (
absolute_total_delta_angle > 40
and absolute_total_delta_angle <= 130
and direction == "Right"
):
bucket = "Right"
return bucket
elif (
absolute_total_delta_angle > 40
and absolute_total_delta_angle <= 130
and direction == "Left"
):
bucket = "Left"
return bucket
elif (
absolute_total_delta_angle > 130
and direction == "Right"
and self.get_relative_displacement() >= 0.10
):
bucket = "Right"
return bucket
elif (
absolute_total_delta_angle > 130
and direction == "Left"
and self.get_relative_displacement() >= 0.10
):
bucket = "Left"
return bucket
elif absolute_total_delta_angle > 130 and direction == "Right":
bucket = "Right-U-Turn"
return bucket
elif absolute_total_delta_angle > 130 and direction == "Left":
bucket = "Left-U-Turn"
return bucket
else:
bucket = "Straight"
return bucket
@staticmethod
def get_gross_direction_for_three_points(
start: pd.DataFrame, intermediate: pd.DataFrame, end: pd.DataFrame
):
"""Returns left, right, or straight depending on the direction of the trajectory.
Args:
start (pd.DataFrame): The coordinates of the starting point.
intermediate (pd.DataFrame): The coordinates of the intermediate point.
end (pd.DataFrame): The coordinates of the ending point.
"""
# Calculate vectors
vector1 = np.array(
(intermediate["X"] - start["X"], intermediate["Y"] - start["Y"])
)
vector2 = np.array((end["X"] - intermediate["X"], end["Y"] - intermediate["Y"]))
# Calculate the cross product of the two vectors
cross_product = np.cross(vector1, vector2)
# Determine direction based on cross product
if cross_product > 0:
direction = "Left"
elif cross_product < 0:
direction = "Right"
else:
direction = "Straight"
return direction
def get_relative_displacement(self):
total_displacement = self.get_total_displacement()
# _, _, width = self.scenario.get_viewport()
relative_displacement = total_displacement / self.get_scenario_width()
return relative_displacement
def get_scenario_width(self):
min_x = self.vector_data[:, 0].min()
max_x = self.vector_data[:, 0].max()
min_y = self.vector_data[:, 1].min()
max_y = self.vector_data[:, 1].max()
width = max_x - min_x
return width
def get_total_displacement(self):
"""Calculates the total displacement of the vehicle with the given coordinates.
Returns:
str: Total displacement of the vehicle.
"""
starting_point = (
self.coordinates["X"][0],
self.coordinates["Y"][0],
)
end_point = (
self.coordinates["X"].iloc[-1],
self.coordinates["Y"].iloc[-1],
)
displacement_vector = (
end_point[0] - starting_point[0],
end_point[1] - starting_point[1],
)
# Calculuating the magnitude of the displacement vector and returning it
return math.sqrt(displacement_vector[0] ** 2 + displacement_vector[1] ** 2)
def plot_marginal_predictions_3d(
self,
vector_data,
predictions=None,
confidences=None,
is_available=None,
gt_marginal=None,
plot_subsampling_rate=2,
prediction_subsampling_rate=5,
prediction_horizon=50,
x_range=(-50, 50),
y_range=(-50, 50),
dpi=80,
):
ax = plt.figure(figsize=(15, 15), dpi=dpi).add_subplot(projection="3d")
V = vector_data
X, idx = V[:, :44], V[:, 44].flatten()
car = np.array(
[
(-2.25, -1, 0), # left bottom front
(-2.25, 1, 0), # left bottom back
(2.25, -1, 0), # right bottom front
(-2.25, -1, 1.5), # left top front -> height
]
)
pedestrian = np.array(
[
(-0.3, -0.3, 0), # left bottom front
(-0.3, 0.3, 0), # left bottom back
(0.3, -0.3, 0), # right bottom front
(-0.3, -0.3, 2), # left top front -> height
]
)
cyclist = np.array(
[
(-1, -0.3, 0), # left bottom front
(-1, 0.3, 0), # left bottom back
(1, -0.3, 0), # right bottom front
(-1, -0.3, 2), # left top front -> height
]
)
for i in np.unique(idx):
_X = X[
(idx == i)
& (X[:, 0] < x_range[1])
& (X[:, 1] < y_range[1])
& (X[:, 0] > x_range[0])
& (X[:, 1] > y_range[0])
]
if _X[:, 8].sum() > 0:
if _X[-1, 0] == 0 and _X[-1, 1] == 0:
plt.plot(_X[:, 0], _X[:, 1], 0, linewidth=4, color="blue")
plt.plot(_X[-1, 0], _X[-1, 1], 0, "o", markersize=10, color="blue")
bbox = self.rotate_bbox_zxis(car, _X[-1, 4])
bbox = self.shift_cuboid(_X[-1, 0], _X[-1, 1], bbox)
if _X[-1, 2]: # speed to determine dynamic or static
self.add_cube(bbox, ax, color="tab:blue", alpha=0.5)
else:
self.add_cube(bbox, ax, color="tab:grey", alpha=0.5)
elif _X[:, 9].sum() > 0:
if _X[-1, 0] == 0 and _X[-1, 1] == 0:
plt.plot(_X[:, 0], _X[:, 1], 0, linewidth=4, color="orange")
plt.plot(
_X[-1, 0], _X[-1, 1], 0, "o", markersize=10, color="orange"
)
bbox = self.rotate_bbox_zxis(pedestrian, _X[-1, 4])
bbox = self.shift_cuboid(_X[-1, 0], _X[-1, 1], bbox)
self.add_cube(bbox, ax, color="tab:orange", alpha=0.5)
elif _X[:, 10].sum() > 0:
if _X[-1, 0] == 0 and _X[-1, 1] == 0:
plt.plot(_X[:, 0], _X[:, 1], 0, linewidth=4, color="green")
plt.plot(_X[-1, 0], _X[-1, 1], 0, "o", markersize=10, color="green")
bbox = self.rotate_bbox_zxis(cyclist, _X[-1, 4])
bbox = self.shift_cuboid(_X[-1, 0], _X[-1, 1], bbox)
self.add_cube(bbox, ax, color="tab:green", alpha=0.5)
elif _X[:, 13:16].sum() > 0: # Traffic lanes
plt.plot(_X[:, 0], _X[:, 1], 0, color="black")
elif _X[:, 16].sum() > 0: # Bike lanes
plt.plot(_X[:, 0], _X[:, 1], 0, color="tab:red")
elif _X[:, 18:26].sum() > 0: # Road lines
plt.plot(_X[:, 0], _X[:, 1], 0, "--", color="grey")
elif _X[:, 26:29].sum() > 0: # Road edges
plt.plot(_X[:, 0], _X[:, 1], 0, linewidth=2, color="grey")
ax.set_zlim(bottom=0, top=5)
ax.set_aspect("equal")
ax.set_axis_off()
ax.set_facecolor("tab:grey")
is_available = is_available[
prediction_subsampling_rate
- 1 : prediction_horizon : prediction_subsampling_rate
]
gt_marginal = gt_marginal[
prediction_subsampling_rate
- 1 : prediction_horizon : prediction_subsampling_rate
]
confids_scaled = self.sigmoid(confidences)
colors = plt.cm.viridis(confidences * 4)
for pred_id in np.argsort(confidences):
confid = confidences[pred_id]
label = f"Pred {pred_id}, confid: {confid:.2f}" if False else ""
confid_scaled = confids_scaled[pred_id]
plt.plot(
np.concatenate(
(
np.array([[0.0, 0.0]]),
predictions[pred_id][is_available > 0][::plot_subsampling_rate],
)
)[:, 0],
np.concatenate(
(
np.array([[0.0, 0.0]]),
predictions[pred_id][is_available > 0][::plot_subsampling_rate],
)
)[:, 1],
"-o",
color=colors[pred_id],
label=label,
linewidth=3, # linewidth,
markersize=10, # linewidth+3,
)
plt.plot(
np.concatenate(
(
np.array([0.0]),
gt_marginal[is_available > 0][:, 0][::plot_subsampling_rate],
)
),
np.concatenate(
(
np.array([0.0]),
gt_marginal[is_available > 0][:, 1][::plot_subsampling_rate],
)
),
"--o",
color="tab:cyan",
label=label,
linewidth=4, # 4
markersize=10,
)
return plt
def plot_scenario(
self,
filename="output/3D_scenario_plot",
x_range=(-180, 180),
y_range=(-180, 180),
prediction_subsampling_rate=8,
prediction_horizon=80,
plot_subsampling_rate=2,
dpi=1000,
is_available=None,
gt_marginal=None,
):
gt_marginal = self.gt_marginal
is_available = self.future_val_marginal
predictions = np.zeros(self.future_val_marginal.shape)
predictions = np.zeros((6, 10, 2))
confidences = np.zeros((6,))
# print(predictions.shape)
# plot = self.plot_marginal_predictions_3d(
# vector_data=self.vector_data,
# is_available=self.future_val_marginal,
# gt_marginal=self.gt_marginal,
# predictions=prediction_dummy,
# confidences=np.zeros((6,)),
# # gt_marginal=npz_trajectory.gt_marginal,
# )
ax = plt.figure(figsize=(10, 10), dpi=dpi).add_subplot(projection="3d")
V = self.vector_data
X, idx = V[:, :44], V[:, 44].flatten()
car = np.array(
[
(-2.25, -1, 0), # left bottom front
(-2.25, 1, 0), # left bottom back
(2.25, -1, 0), # right bottom front
(-2.25, -1, 1.5), # left top front -> height
]
)
pedestrian = np.array(
[
(-0.3, -0.3, 0), # left bottom front
(-0.3, 0.3, 0), # left bottom back
(0.3, -0.3, 0), # right bottom front
(-0.3, -0.3, 2), # left top front -> height
]
)
cyclist = np.array(
[
(-1, -0.3, 0), # left bottom front
(-1, 0.3, 0), # left bottom back
(1, -0.3, 0), # right bottom front
(-1, -0.3, 2), # left top front -> height
]
)
# print(X[0])
# print(np.unique(idx).shape)
# print(np.unique(idx))
# print(X[(idx == 220)].shape)
# print(X[X[:, 8] == 1].shape)
# print(X[(idx == 0)][:, 0])
# print(X.shape)
for i in np.unique(idx):
_X = X[
(idx == i)
& (X[:, 0] < x_range[1])
& (X[:, 1] < y_range[1])
& (X[:, 0] > x_range[0])
& (X[:, 1] > y_range[0])
]
# print(_X.shape)
if _X[:, 8].sum() > 0:
# The ego vehicle in this scenario starts at (0, 0). This is checked in the next line.
# if _X[-1, 0] == 0 and _X[-1, 1] == 0:
# plt.plot(_X[:, 0], _X[:, 1], 0, linewidth=4, color="red")
# plt.plot(_X[-1, 0], _X[-1, 1], 0, "o", markersize=10, color="blue")
# plt.plot(_X[-1, 0], _X[-1, 1], 0, linewidth=4, color="red")
bbox = self.rotate_bbox_zxis(car, _X[-1, 4])
bbox = self.shift_cuboid(_X[-1, 0], _X[-1, 1], bbox)
if _X[-1, 2]: # speed to determine dynamic or static
self.add_cube(bbox, ax, color="tab:blue", alpha=0.5)
else:
self.add_cube(bbox, ax, color="tab:grey", alpha=0.5)
elif _X[:, 9].sum() > 0:
if _X[-1, 0] == 0 and _X[-1, 1] == 0:
plt.plot(_X[:, 0], _X[:, 1], 0, linewidth=1, color="orange")
# plt.plot(
# _X[-1, 0], _X[-1, 1], 0, "o", markersize=10, color="orange"
# )
bbox = self.rotate_bbox_zxis(pedestrian, _X[-1, 4])
bbox = self.shift_cuboid(_X[-1, 0], _X[-1, 1], bbox)
self.add_cube(bbox, ax, color="tab:orange", alpha=0.5)
elif _X[:, 10].sum() > 0: # Bike
if _X[-1, 0] == 0 and _X[-1, 1] == 0:
plt.plot(_X[:, 0], _X[:, 1], 0, linewidth=4, color="green")
plt.plot(_X[-1, 0], _X[-1, 1], 0, "o", markersize=10, color="green")
bbox = self.rotate_bbox_zxis(cyclist, _X[-1, 4])
bbox = self.shift_cuboid(_X[-1, 0], _X[-1, 1], bbox)
self.add_cube(bbox, ax, color="tab:green", alpha=0.5)
elif _X[:, 13:16].sum() > 0: # Traffic lanes
# print("Something to plot")
# print(_X[:, 13:16])
# print(_X[:, 13:16].shape)
plt.plot(
_X[:, 0],
_X[:, 1],
0,
c=np.random.rand(
3,
),
)
# plt.plot(_X[:, 0], _X[:, 1], 0, color="black")
elif _X[:, 16].sum() > 0: # Bike lanes
plt.plot(_X[:, 0], _X[:, 1], 0, color="tab:red")
elif _X[:, 18:26].sum() > 0: # Road lines
plt.plot(_X[:, 0], _X[:, 1], 0, "--", color="grey")
elif _X[:, 26:29].sum() > 0: # Road edges
plt.plot(_X[:, 0], _X[:, 1], 0, linewidth=2, color="grey")
# elif _X[:, 29].sum() > 0: # Test
# plt.plot(_X[:, 0], _X[:, 1], 0, color="orange", linewidth=1)
# elif _X[:, 30].sum() > 0: # Stop Signs
# # print(_X[:, 30])
# x = _X[:, 0]
# y = _X[:, 1]
# z = 0
# plt.plot(
# x,
# y,
# 0,
# color="red",
# marker="8",
# markersize=22,
# markeredgewidth=1,
# markeredgecolor="black",
# )
# for i in range(len(x)):
# ax.text(
# x[i],
# y[i],
# z,
# "STOP",
# color="white",
# ha="center",
# va="center",
# fontsize=6,
# weight="bold",
# ) # Adds "Stop" text
# elif _X[:, 31].sum() > 0: # Crosswalks
# x = _X[:, 0]
# y = _X[:, 1]
# z = 0
# plt.plot(
# x,
# y,
# 0,
# linestyle="dashed",
# dashes=(0.2, 0.2),
# color="black",
# linewidth=15,
# )
# elif _X[:, 32].sum() > 0: # Speedbumps
# x = _X[:, 0]
# y = _X[:, 1]
# z = 0
# plt.plot(x, y, 0, color="green", marker="o")
# line_length = 2 # Length of the entire speed bump line
# stripe_length = 0.2 # Length of each stripe
# stripe_width = 1 # Width of the stripes, making it look more line-like
# for i in range(len(x)):
# start_x = x[i] - line_length / 2
# end_x = x[i] + line_length / 2
# current_x = start_x
# while current_x < end_x:
# # Alternating colors for stripes
# color = (
# "yellow"
# if (current_x - start_x) // stripe_length % 2 == 0
# else "black"
# )
# # Plot each stripe as a thin rectangle (or extended line)
# ax.plot(
# [current_x, current_x + stripe_length],
# [y[i], y[i]],
# [z, z],
# color=color,
# linewidth=stripe_width,
# )
# current_x += stripe_length
# elif _X[:, 32].sum() > 0: # Driveways
# x = _X[:, 0]
# y = _X[:, 1]
# z = 0
# plt.plot(x, y, 0, linewidth=10, alpha=0.7, color="orange")
ax.set_zlim(bottom=0, top=5)
ax.set_aspect("equal")
ax.set_axis_off()
ax.set_facecolor("white")
is_available = is_available[
prediction_subsampling_rate
- 1 : prediction_horizon : prediction_subsampling_rate
]
gt_marginal = gt_marginal[
prediction_subsampling_rate
- 1 : prediction_horizon : prediction_subsampling_rate
]
confids_scaled = self.sigmoid(confidences)
colors = plt.cm.viridis(confidences * 4)
for pred_id in np.argsort(confidences):
confid = confidences[pred_id]
label = f"Pred {pred_id}, confid: {confid:.2f}" if False else ""
confid_scaled = confids_scaled[pred_id]
# plt.plot(
# np.concatenate(
# (
# np.array([[0.0, 0.0]]),
# predictions[pred_id][is_available > 0][::plot_subsampling_rate],
# )
# )[:, 0],
# np.concatenate(
# (
# np.array([[0.0, 0.0]]),
# predictions[pred_id][is_available > 0][::plot_subsampling_rate],
# )
# )[:, 1],
# "-o",
# color=colors[pred_id],
# label=label,
# linewidth=3, # linewidth,
# markersize=10, # linewidth+3,
# )
# plt.plot(
# np.concatenate(
# (
# np.array([0.0]),
# gt_marginal[is_available > 0][:, 0][::plot_subsampling_rate],
# )
# ),
# np.concatenate(
# (
# np.array([0.0]),
# gt_marginal[is_available > 0][:, 1][::plot_subsampling_rate],
# )
# ),
# "--o",
# color="tab:cyan",
# label=label,
# linewidth=4, # 4
# markersize=10,
# )
# plt.plot(
# np.concatenate(
# (
# np.array([0.0]),
# gt_marginal[is_available > 0][:, 0][::plot_subsampling_rate],
# )
# ),
# np.concatenate(
# (
# np.array([0.0]),
# gt_marginal[is_available > 0][:, 1][::plot_subsampling_rate],
# )
# ),
# color="tab:red",
# label=label,
# linewidth=4,
# )
plt.savefig(filename)
def plot_trajectory(
self,
filename="output/3D_trajectory_plot",
x_range=(-50, 50),
y_range=(-50, 50),
prediction_subsampling_rate=8,
prediction_horizon=80,
plot_subsampling_rate=2,
dpi=1000,
is_available=None,
gt_marginal=None,
):
gt_marginal = self.gt_marginal
is_available = self.future_val_marginal
predictions = np.zeros(self.future_val_marginal.shape)
predictions = np.zeros((6, 10, 2))
confidences = np.zeros((6,))
# print(predictions.shape)
# plot = self.plot_marginal_predictions_3d(
# vector_data=self.vector_data,
# is_available=self.future_val_marginal,
# gt_marginal=self.gt_marginal,
# predictions=prediction_dummy,
# confidences=np.zeros((6,)),
# # gt_marginal=npz_trajectory.gt_marginal,
# )
ax = plt.figure(figsize=(10, 10), dpi=dpi).add_subplot(projection="3d")
V = self.vector_data
X, idx = V[:, :44], V[:, 44].flatten()
car = np.array(
[
(-2.25, -1, 0), # left bottom front
(-2.25, 1, 0), # left bottom back
(2.25, -1, 0), # right bottom front
(-2.25, -1, 1.5), # left top front -> height
]
)
pedestrian = np.array(
[
(-0.3, -0.3, 0), # left bottom front
(-0.3, 0.3, 0), # left bottom back
(0.3, -0.3, 0), # right bottom front
(-0.3, -0.3, 2), # left top front -> height
]
)
cyclist = np.array(
[
(-1, -0.3, 0), # left bottom front
(-1, 0.3, 0), # left bottom back
(1, -0.3, 0), # right bottom front
(-1, -0.3, 2), # left top front -> height
]
)
# print(X[0])
# print(np.unique(idx).shape)
# print(np.unique(idx))
# print(X[(idx == 220)].shape)
# print(X[X[:, 8] == 1].shape)
# print(X[(idx == 0)][:, 0])
# print(X.shape)
for i in np.unique(idx):
_X = X[
(idx == i)
& (X[:, 0] < x_range[1])
& (X[:, 1] < y_range[1])
& (X[:, 0] > x_range[0])
& (X[:, 1] > y_range[0])
]
# print(_X.shape)
if _X[:, 8].sum() > 0:
# The ego vehicle in this scenario starts at (0, 0). This is checked in the next line.
if _X[-1, 0] == 0 and _X[-1, 1] == 0:
plt.plot(_X[:, 0], _X[:, 1], 0, linewidth=4, color="red")
plt.plot(_X[-1, 0], _X[-1, 1], 0, "o", markersize=10, color="blue")
# plt.plot(_X[-1, 0], _X[-1, 1], 0, linewidth=4, color="red")
bbox = self.rotate_bbox_zxis(car, _X[-1, 4])
bbox = self.shift_cuboid(_X[-1, 0], _X[-1, 1], bbox)
if _X[-1, 2]: # speed to determine dynamic or static
self.add_cube(bbox, ax, color="tab:blue", alpha=0.5)
else:
self.add_cube(bbox, ax, color="tab:grey", alpha=0.5)
elif _X[:, 9].sum() > 0:
# if _X[-1, 0] == 0 and _X[-1, 1] == 0:
# plt.plot(_X[:, 0], _X[:, 1], 0, linewidth=4, color="orange")
# plt.plot(
# _X[-1, 0], _X[-1, 1], 0, "o", markersize=10, color="orange"
# )
bbox = self.rotate_bbox_zxis(pedestrian, _X[-1, 4])
bbox = self.shift_cuboid(_X[-1, 0], _X[-1, 1], bbox)
self.add_cube(bbox, ax, color="tab:orange", alpha=0.5)
elif _X[:, 10].sum() > 0:
if _X[-1, 0] == 0 and _X[-1, 1] == 0:
plt.plot(_X[:, 0], _X[:, 1], 0, linewidth=4, color="green")
plt.plot(_X[-1, 0], _X[-1, 1], 0, "o", markersize=10, color="green")
bbox = self.rotate_bbox_zxis(cyclist, _X[-1, 4])
bbox = self.shift_cuboid(_X[-1, 0], _X[-1, 1], bbox)
self.add_cube(bbox, ax, color="tab:green", alpha=0.5)
elif _X[:, 13:16].sum() > 0: # Traffic lanes
# print("Something to plot")
# print(_X[:, 13:16])
# print(_X[:, 13:16].shape)
plt.plot(_X[:, 0], _X[:, 1], 0, color="black")
elif _X[:, 16].sum() > 0: # Bike lanes
plt.plot(_X[:, 0], _X[:, 1], 0, color="tab:red")
elif _X[:, 18:26].sum() > 0: # Road lines
plt.plot(_X[:, 0], _X[:, 1], 0, "--", color="grey")
elif _X[:, 26:29].sum() > 0: # Road edges
plt.plot(_X[:, 0], _X[:, 1], 0, linewidth=2, color="grey")
ax.set_zlim(bottom=0, top=5)
ax.set_aspect("equal")
ax.set_axis_off()
ax.set_facecolor("white")
is_available = is_available[
prediction_subsampling_rate
- 1 : prediction_horizon : prediction_subsampling_rate
]
gt_marginal = gt_marginal[
prediction_subsampling_rate
- 1 : prediction_horizon : prediction_subsampling_rate
]
confids_scaled = self.sigmoid(confidences)
colors = plt.cm.viridis(confidences * 4)
for pred_id in np.argsort(confidences):
confid = confidences[pred_id]
label = f"Pred {pred_id}, confid: {confid:.2f}" if False else ""
confid_scaled = confids_scaled[pred_id]
# plt.plot(
# np.concatenate(
# (
# np.array([[0.0, 0.0]]),
# predictions[pred_id][is_available > 0][::plot_subsampling_rate],
# )
# )[:, 0],
# np.concatenate(
# (
# np.array([[0.0, 0.0]]),
# predictions[pred_id][is_available > 0][::plot_subsampling_rate],
# )
# )[:, 1],
# "-o",
# color=colors[pred_id],
# label=label,
# linewidth=3, # linewidth,
# markersize=10, # linewidth+3,
# )
# plt.plot(
# np.concatenate(
# (
# np.array([0.0]),
# gt_marginal[is_available > 0][:, 0][::plot_subsampling_rate],
# )
# ),
# np.concatenate(
# (
# np.array([0.0]),
# gt_marginal[is_available > 0][:, 1][::plot_subsampling_rate],
# )
# ),
# "--o",
# color="tab:cyan",
# label=label,
# linewidth=4, # 4
# markersize=10,
# )
plt.plot(
np.concatenate(
(
np.array([0.0]),
gt_marginal[is_available > 0][:, 0][::plot_subsampling_rate],
)
),
np.concatenate(
(
np.array([0.0]),
gt_marginal[is_available > 0][:, 1][::plot_subsampling_rate],
)
),
color="tab:red",
label=label,
linewidth=2,
)
plt.tight_layout()
ax.margins(x=0, y=0)