forked from PaulKMueller/llama_traffic
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcli.py
3855 lines (3185 loc) · 129 KB
/
cli.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 sys
import cmd
import argparse
import os
from typing import Tuple
import yaml
import json
import math
import keras
import io
from tqdm import tqdm
import seaborn as sns
import time
from PIL import Image
import wandb
from wandb.keras import WandbMetricsLogger
import tensorflow as tf
from tensorflow.keras.losses import MeanSquaredError
import matplotlib.pyplot as plt
from npz_utils import (
list_vehicle_files_absolute,
one_hot_encode_trajectory,
decode_one_hot_vector,
SCENARIO_LABEL_LIST,
)
import pandas as pd
from datetime import datetime
# from training_dataclass import TrainingData
from trajectory import Trajectory
import numpy as np
import random
from npz_trajectory import NpzTrajectory
from ego_trajectory_encoder import EgoTrajectoryEncoder
# from llama_test import get_llama_embeddingK
from cohere_encoder import get_cohere_encoding
from uae_explore import get_uae_encoding
# from voyage_explore import get_voyage_encoding
# from training_dataclass import TrainingData
import torch
from learning.rnns import train_lstm_neural_network
from waymo_inform import (
create_labeled_ego_trajectories,
plot_trajectory_by_id,
get_trajectories_for_text_input,
visualize_raw_coordinates_without_scenario,
get_vehicles_for_scenario,
create_labeled_trajectories_for_scenario,
create_zipped_labeled_trajectories_for_all_scenarios_json,
get_labeled_trajectories_for_all_scenarios_json,
)
from learning.trajectory_generator import (
infer_with_simple_neural_network,
train_simple_neural_network,
infer_with_neural_network,
train_neural_network,
)
from learning.transformer_encoder import (
positional_encoding,
PositionalEmbedding,
GlobalSelfAttention,
FeedForward,
EncoderLayer,
Encoder,
CrossAttention,
CausalSelfAttention,
DecoderLayer,
Decoder,
Transformer,
CustomSchedule,
train_transformer,
)
from learning.rnns import train_rnn_neural_network
# from learning.multi_head_attention import get_positional_encoding
from waymo_utils import (
get_scenario_list,
get_scenario_index,
)
from bert_encoder import get_bert_embedding, init_bucket_embeddings, test_bert_encoding
from learning.trajectory_classifier import train_classifier
from scenario import Scenario
class SimpleShell(cmd.Cmd):
prompt = "(waymo_cli) "
loaded_scenario = None
loaded_trajectory = None
loaded_npz_trajectory = None
with open("config.yml", "r") as file:
config = yaml.safe_load(file)
scenario_data_folder = config["scenario_data_folder"]
def arg_parser(self):
# Initializing the available flags for the different commands.
parser = argparse.ArgumentParser()
parser.add_argument("-n", "--name", default="World")
parser.add_argument("-p", "--path")
parser.add_argument("--ids", action="store_true")
parser.add_argument("--index")
parser.add_argument("--example", "-e", action="store_true")
return parser
def do_greet(self, arg: str):
"""Prints a greeting to the user whose name is provided as an argument.
The format of the command is: greet --name <NAME>
or: greet -n <NAME>
Args:
arg (str): The name of the user to greet.
"""
try:
parsed = self.arg_parser().parse_args(arg.split())
print(f"Hello, {parsed.name}!")
except SystemExit:
pass # argparse calls sys.exit(), catch the exception to prevent shell exit
def do_plot_map(self, arg: str):
"""Plots the map for the loaded scenario."""
# Load config file
with open("config.yml", "r") as file:
config = yaml.safe_load(file)
output_folder = config["output_folder"]
# Checking if a scenario has been loaded already.
if not self.scenario_loaded():
return
image = self.loaded_scenario.visualize_map()
image.savefig(
f"{output_folder}roadgraph_{get_scenario_index(self.loaded_scenario.name)}.png"
)
def do_visualize_trajectory(self, arg: str):
"""Plots the trajectory for the given vehicle ID."""
# Load config file
with open("config.yml", "r") as file:
config = yaml.safe_load(file)
output_folder = config["output_folder"]
# Checking if a scenario has been loaded already.
if not self.scenario_loaded():
return
# Check for empty arguments (no ID provided)
if arg == "":
print(
(
"\nYou have provided no ID for the vehicle "
"that you want to plot.\nPlease provide a path!\n"
)
)
return
vehicle_id = arg.split()[0]
trajectory = Trajectory(self.loaded_scenario, vehicle_id)
trajectory_plot = self.loaded_scenario.visualize_coordinates(
trajectory.coordinates, title=f"Trajectory {vehicle_id}"
)
trajectory_plot.savefig(f"{output_folder}{vehicle_id}.png")
def do_store_full_raw_scenario(self, arg: str):
# TODO: Check for loaded scenario
dataset = tf.data.TFRecordDataset(
self.loaded_scenario.path, compression_type=""
)
data = next(dataset.as_numpy_iterator())
with open("output/raw_scenario.txt", "w") as file:
file.write(str(data))
def do_load_scenario(self, arg: str):
"""Loads the scenario from the given path.
The format of the command is: load_scenario <PATH>
or: load_scenario --example
or: load_scenario -e
Args:
arg (str): The path to the scenario that should be loaded.
Alternatively, the flag --example or -e can be used to load
a pre-defined example scenario.
"""
# Load config file
with open("config.yml", "r") as file:
config = yaml.safe_load(file)
scenario_data_folder = config["scenario_data_folder"]
example_scenario_path = config["example_scenario_path"]
args = arg.split()
# Check for empty arguments (no path provided)
print("The scenario is being loaded...")
if arg == "":
print(
"\nYou have provided no path for the scenario you want to load."
"\nPlease provide a path!\n"
)
return
elif args[0] == "-e" or args[0] == "--example":
self.loaded_scenario = Scenario(example_scenario_path)
print("Successfully initialized the example scenario!")
return
elif args[0] == "-p" or args[0] == "--path":
filename = args[1]
self.loaded_scenario = Scenario(scenario_path=filename)
print("\nSuccessfully initialized the given scenario!\n")
return
elif args[0] == "-i" or args[0] == "--index":
scenario_name = get_scenario_list()[int(args[1])]
self.loaded_scenario = Scenario(
scenario_path=scenario_data_folder + scenario_name
)
print("\nSuccessfully initialized the given scenario!\n")
return
else:
print(
"""Invalid input, please try again.
Use -p to specify the scenario path, -i to specify the scenario index
or - e to load the example scenario chosen in your config.yml."""
)
def do_test_npz_bucketing(self, arg: str):
npz_files = list_vehicle_files_absolute()
output = {}
for file in tqdm(npz_files):
npz_trajectory = NpzTrajectory(file)
output[file] = npz_trajectory.direction
with open("output/npz_bucketing_test.json", "w") as file:
json.dump(output, file)
def do_load_npz_trajectory(
self,
arg: str = "/storage_local/fzi_datasets_tmp/waymo_open_motion_dataset/unzipped/train-2e6/vehicle_d_13657_00002_4856147881.npz",
):
# vehicle is type 1, pedestrian type 2
# npz_trajectory = NpzTrajectory(
# "/mrtstorage/datasets/tmp/waymo_open_motion_processed/train-2e6/vehicle_a_67582_00003_5913311279.npz"
# )
# print(os.listdir("/storage_local/fzi_datasets_tmp/waymo_open_motion_dataset/unzipped/train-2e6"))
# npz_trajectory = NpzTrajectory(
# "/storage_local/fzi_datasets_tmp/waymo_open_motion_dataset/unzipped/train-2e6/vehicle_d_13657_00002_4856147881.npz"
# )
with open("config.yml") as config:
cfg = yaml.safe_load(config)
data_folder = "/storage_local/fzi_datasets_tmp/waymo_open_motion_dataset/unzipped/train-2e6/"
npz_filepath = data_folder + arg
npz_trajectory = NpzTrajectory(npz_filepath)
# npz_trajectory = NpzTrajectory(
# "/home/pmueller/llama_traffic/datasets/npz_test_data/train-2e6/pedestrian_c_77063_00004_7456769354.npz"
# )
self.loaded_npz_trajectory = npz_trajectory
# print(npz_trajectory._gt_marginal)
x = npz_trajectory._gt_marginal[:, 0]
y = npz_trajectory._gt_marginal[:, 1]
# print(x)
# print(y)
coordinates = pd.DataFrame({"X": x, "Y": y})
npz_plot = npz_trajectory.visualize_raw_coordinates_without_scenario(
coordinates
)
# npz_plot.savefig("output/test_npz_plot.png")
# print(npz_trajectory.get_delta_angles(npz_trajectory.coordinates))
# print(npz_trajectory.movement_vectors)
# print(npz_trajectory.get_sum_of_delta_angles())
# plot = npz_trajectory.plot_marginal_predictions_3d(npz_trajectory.vector_data)
predictions = np.zeros(npz_trajectory.future_val_marginal.shape)
prediction_dummy = np.zeros((6, 10, 2))
# print(type(prediction_dummy))
# print(npz_trajectory.future_val_marginal.shape)
# print(npz_trajectory.future_val_marginal)
# print(predictions.shape)
# plot = npz_trajectory.plot_marginal_predictions_3d(
# vector_data=npz_trajectory.vector_data,
# is_available=npz_trajectory.future_val_marginal,
# gt_marginal=npz_trajectory.gt_marginal,
# predictions=prediction_dummy,
# confidences=np.zeros((6,)),
# # gt_marginal=npz_trajectory.gt_marginal,
# )
# npz_trajectory.plot_trajectory()
# print(npz_trajectory.direction)
def do_plot_npz_trajectory(self, arg: str):
if self.loaded_npz_trajectory == None:
print(
"No NPZ trajectory has been loaded yet. Please load a scenario before calling this command."
)
return
self.loaded_npz_trajectory.plot_trajectory()
def do_plot_npz_scenario(self, arg: str):
if self.loaded_npz_trajectory == None:
print(
"No NPZ trajectory has been loaded yet. Please load a scenario before calling this command."
)
return
self.loaded_npz_trajectory.plot_scenario()
def do_animate_npz_trajectory(self, arg: str):
if self.loaded_npz_trajectory == None:
print(
"No NPZ trajectory has been loaded yet. Please load a scenario before calling this command."
)
return
self.loaded_npz_trajectory.animate_scenario_past()
def do_create_intra_distribution_for(self, arg: str):
with open("config.yml") as config:
config = yaml.safe_load(config)
npz_dataset = config["npz_dataset"]
chosen_bucket = arg
bucket_indeces = {
"Left": 0,
"Right": 0,
"Stationary": 0,
"Straight": 0,
"Straight-Left": 0,
"Straight-Right": 0,
"Right-U-Turn": 0,
"Left-U-Turn": 0,
}
bucket_cos_sim_sum = np.zeros(8)
with open("datasets/similarity_dataset.json") as similarities:
similarity_data = json.load(similarities)
similarity_data_keys = list(similarity_data.keys())
similarity_data_keys = [
key
for key in similarity_data_keys
if NpzTrajectory(npz_dataset + key).direction == arg
]
print(len(similarity_data_keys))
for key in similarity_data_keys:
sim_data_for_entry = np.array(similarity_data[key])
bucket_cos_sim_sum += sim_data_for_entry
print(np.divide(bucket_cos_sim_sum, 468108))
def do_create_direction_labeled_npz_dataset(self, arg: str):
with open("config.yml") as config:
config = yaml.safe_load(config)
npz_directory = "/storage_local/fzi_datasets_tmp/waymo_open_motion_dataset/unzipped/train-2e6/"
bucket_indeces = {
"Left": 0,
"Right": 1,
"Stationary": 2,
"Straight": 3,
"Straight-Left": 4,
"Straight-Right": 5,
"Right-U-Turn": 6,
"Left-U-Turn": 7,
}
print("Config read!")
output = {}
trajectory_paths = list_vehicle_files_absolute(npz_directory)
print("Trajectories listed!")
with open("output/direction_labeled_npz_vehicle_a.json", "a") as file:
file.write("{")
for i in tqdm(range(len(trajectory_paths))):
path = trajectory_paths[i]
npz_trajectory = NpzTrajectory(path)
file.write(
f"{path.split('/')[-1]}: {bucket_indeces[npz_trajectory.direction]},\n"
)
# output[path.split("/")[-1]] = bucket_indeces[npz_trajectory.direction]
# coordinates = list(
# zip(npz_trajectory.coordinates["X"], npz_trajectory.coordinates["Y"])
# )
# local_dict = {
# "Coordinates": coordinates,
# "Direction": npz_trajectory.direction,
# }
# output[path] = local_dict
# with open("output/direction_labeled_npz_vehicle_a.json", "a") as file:
# file.write(f'"{path.split("/")[-1]}": {local_dict},\n')
file.write("}")
def do_create_trajectory_encoder_labeled_npz_dataset(self, arg: str):
torch.set_printoptions(profile="full")
model = EgoTrajectoryEncoder()
model.load_state_dict(
torch.load(
"/home/pmueller/llama_traffic/models/trajectory_encoder_wv_cos.pth"
)
)
model.eval()
model.to("cuda")
with torch.no_grad():
with open("datasets/direction_labeled_npz_vehicle_a.json") as file:
data_json = json.load(file)
keys = list(data_json.keys())
# coordinates = torch.Tensor(item["Coordinates"] for item in list(data_json.values()))
with open("datasets/encoder_output_vehicle_a_cos.json", "a") as output:
output.write("{")
for i in tqdm(range(len(keys))):
key = keys[i]
coordinates = torch.Tensor(data_json[key]["Coordinates"]).to(
"cuda"
)
encoder_output = model(coordinates.unsqueeze(0)).squeeze()
output.write(
f'"{key.split("/")[-1]}" : {encoder_output.tolist()}'
+ ",\n"
)
output.write("}")
def do_plot_random_npz_trajectory(self, arg: str):
with open("config.yml") as config:
config = yaml.safe_load(config)
data_directory = config["npz_dataset"]
vehicles_file_paths = list_vehicle_files_absolute(data_directory)
chosen_vehicle = random.choice(vehicles_file_paths)
npz_trajectory = NpzTrajectory(chosen_vehicle)
npz_trajectory.plot_trajectory()
npz_trajectory.plot_scenario()
print(chosen_vehicle)
def do_plot_random_test_npz_trajectories(self, arg: str):
labels = {}
names = {}
with open("config.yml") as config:
config = yaml.safe_load(config)
data_directory = config["npz_dataset"]
vehicles_file_paths = list_vehicle_files_absolute(data_directory)
for i in tqdm(range(100)):
chosen_vehicle = random.choice(vehicles_file_paths)
npz_trajectory = NpzTrajectory(chosen_vehicle)
# npz_trajectory.plot_trajectory(filename=f"output/{i}.png")
raw_trajectory_plot = visualize_raw_coordinates_without_scenario(
npz_trajectory.coordinates["X"],
npz_trajectory.coordinates["Y"],
title=i,
)
raw_trajectory_plot.savefig(f"output/{i}.png")
labels[i] = npz_trajectory.direction
names[i] = npz_trajectory.path
# npz_trajectory.plot_scenario()
with open("output/labels_test.json", "w") as labels_file:
json.dump(labels, labels_file, indent=4)
with open("output/names_test.json", "w") as names_file:
json.dump(names, names_file, indent=4)
def do_has_feature(self, arg: str):
if arg == "":
print("No feature given!")
return
features = {
"position_x": 0,
"position_y": 1,
"speed": 2,
"velocity_yaw": 3,
"bbox_yaw": 4,
"length": 5,
"width": 6,
"agent_unset": 7,
"agent_vehicle": 8,
"agent_pedestrian": 9,
"agent_cyclist": 10,
"agent_other": 11,
"IDX_NOT_USED": 33,
"lane_center_undefined": 13,
"lane_center_freeway": 14,
"lane_center_surface_street": 15,
"lane_center_bike_lane": 16,
"road_line_unknowm": 17,
"road_line_broken_single_white": 18,
"road_line_solid_single_white": 19,
"road_line_solid_double_white": 20,
"road_line_broken_single_yellow": 21,
"road_line_broken_double_yellow": 22,
"road_line_solid_single_yellow": 23,
"road_line_solid_double_yellow": 24,
"road_line_passing_double_yellow": 25,
"road_edge_unknown": 26,
"road_edge_boundary": 27,
"road_edge_median": 28,
"stop_sign": 29,
"crosswalk": 30,
"speed_bump": 31,
"driveway": 32,
"IDX_NOT_USED": 33,
"traffic_light_state_unknown": 34,
"traffic_light_state_arrow_stop": 35,
"traffic_light_state_arrow_caution": 36,
"traffic_light_state_arrow_go": 37,
"traffic_light_state_stop": 38,
"traffic_light_state_caution": 39,
"traffic_light_state_go": 40,
"traffic_light_state_flashing_stop": 41,
"traffic_light_state_flashing_caution": 42,
"timestamp": 43,
"global_idx": 44,
}
# vehicle_path = "/storage_local/fzi_datasets_tmp/waymo_open_motion_dataset/unzipped/train-2e6/vehicle_d_13657_00002_4856147881.npz"
# vehicle_path = "/storage_local/fzi_datasets_tmp/waymo_open_motion_dataset/unzipped/train-2e6/vehicle_a_25972_00006_9317225410.npz"
# /storage_local/fzi_datasets_tmp/waymo_open_motion_dataset/unzipped/train-2e6/vehicle_a_84559_00003_3143712003.npz
# /storage_local/fzi_datasets_tmp/waymo_open_motion_dataset/unzipped/train-2e6/vehicle_a_80216_00003_536845315.npz
# /storage_local/fzi_datasets_tmp/waymo_open_motion_dataset/unzipped/train-2e6/vehicle_a_82420_00002_2301414027.npz
# /storage_local/fzi_datasets_tmp/waymo_open_motion_dataset/unzipped/train-2e6/vehicle_a_62891_00004_7533961705.npz
# /storage_local/fzi_datasets_tmp/waymo_open_motion_dataset/unzipped/train-2e6/vehicle_a_31226_00003_532688195.npz
# /storage_local/fzi_datasets_tmp/waymo_open_motion_dataset/unzipped/train-2e6/vehicle_a_114724_00000_389619377.npz
# /storage_local/fzi_datasets_tmp/waymo_open_motion_dataset/unzipped/train-2e6/vehicle_a_39001_00001_6094040646.npz
# /storage_local/fzi_datasets_tmp/waymo_open_motion_dataset/unzipped/train-2e6/vehicle_a_10749_00002_3702461762.npz
# /storage_local/fzi_datasets_tmp/waymo_open_motion_dataset/unzipped/train-2e6/vehicle_a_115558_00002_7015306401.npz
# /storage_local/fzi_datasets_tmp/waymo_open_motion_dataset/unzipped/train-2e6/vehicle_a_25972_00006_9317225410.npz
vehicle_path = self.loaded_npz_trajectory.path
with np.load(vehicle_path) as data:
V = data["vector_data"]
X, idx = V[:, :44], V[:, 44].flatten()
np.set_printoptions(threshold=sys.maxsize)
for i in np.unique(idx):
_X = X[i == idx]
try:
numeric_key = features[arg]
if _X[:, numeric_key].sum() > 0:
print(True)
return
# print(X[:, numeric_key])
# print(X.shape)
# else:
# print(False)
# print(X[:, numeric_key])
# print(numeric_key)
except KeyError:
print(f"No feature named {arg} exists!")
print(False)
def do_print_feature_coordinates(self, arg: str):
if arg == "":
print("No feature given!")
return
features = {
"position_x": 0,
"position_y": 1,
"speed": 2,
"velocity_yaw": 3,
"bbox_yaw": 4,
"length": 5,
"width": 6,
"agent_unset": 7,
"agent_vehicle": 8,
"agent_pedestrian": 9,
"agent_cyclist": 10,
"agent_other": 11,
"IDX_NOT_USED": 33,
"lane_center_undefined": 13,
"lane_center_freeway": 14,
"lane_center_surface_street": 15,
"lane_center_bike_lane": 16,
"road_line_unknowm": 17,
"road_line_broken_single_white": 18,
"road_line_solid_single_white": 19,
"road_line_solid_double_white": 20,
"road_line_broken_single_yellow": 21,
"road_line_broken_double_yellow": 22,
"road_line_solid_single_yellow": 23,
"road_line_solid_double_yellow": 24,
"road_line_passing_double_yellow": 25,
"road_edge_unknown": 26,
"road_edge_boundary": 27,
"road_edge_median": 28,
"stop_sign": 29,
"crosswalk": 30,
"speed_bump": 31,
"driveway": 32,
"IDX_NOT_USED": 33,
"traffic_light_state_unknown": 34,
"traffic_light_state_arrow_stop": 35,
"traffic_light_state_arrow_caution": 36,
"traffic_light_state_arrow_go": 37,
"traffic_light_state_stop": 38,
"traffic_light_state_caution": 39,
"traffic_light_state_go": 40,
"traffic_light_state_flashing_stop": 41,
"traffic_light_state_flashing_caution": 42,
"timestamp": 43,
"global_idx": 44,
}
# vehicle_path = "/storage_local/fzi_datasets_tmp/waymo_open_motion_dataset/unzipped/train-2e6/vehicle_d_13657_00002_4856147881.npz"
# vehicle_path = "/storage_local/fzi_datasets_tmp/waymo_open_motion_dataset/unzipped/train-2e6/vehicle_a_25972_00006_9317225410.npz"
# vehicle_path = "/storage_local/fzi_datasets_tmp/waymo_open_motion_dataset/unzipped/train-2e6/vehicle_a_84559_00003_3143712003.npz"
# vehicle_path = "/storage_local/fzi_datasets_tmp/waymo_open_motion_dataset/unzipped/train-2e6/vehicle_a_80216_00003_536845315.npz"
# vehicle_path = "/storage_local/fzi_datasets_tmp/waymo_open_motion_dataset/unzipped/train-2e6/vehicle_a_82420_00002_2301414027.npz"
# vehicle_path = "/storage_local/fzi_datasets_tmp/waymo_open_motion_dataset/unzipped/train-2e6/vehicle_a_62891_00004_7533961705.npz"
# vehicle_path = "/storage_local/fzi_datasets_tmp/waymo_open_motion_dataset/unzipped/train-2e6/vehicle_a_31226_00003_532688195.npz"
# vehicle_path = "/storage_local/fzi_datasets_tmp/waymo_open_motion_dataset/unzipped/train-2e6/vehicle_a_114724_00000_389619377.npz"
# vehicle_path = "/storage_local/fzi_datasets_tmp/waymo_open_motion_dataset/unzipped/train-2e6/vehicle_a_39001_00001_6094040646.npz"
# Has driveway:
# vehicle_path = "/storage_local/fzi_datasets_tmp/waymo_open_motion_dataset/unzipped/train-2e6/vehicle_a_115558_00002_7015306401.npz"
# vehicle_path = "/storage_local/fzi_datasets_tmp/waymo_open_motion_dataset/unzipped/train-2e6/vehicle_a_10749_00002_3702461762.npz"
# vehicle_path = "/storage_local/fzi_datasets_tmp/waymo_open_motion_dataset/unzipped/train-2e6/vehicle_a_25972_00006_9317225410.npz"
# with np.load(vehicle_path) as data:
# V = data["vector_data"]
# X = V[:, :45]
# np.set_printoptions(threshold=sys.maxsize)
vehicle_path = self.loaded_npz_trajectory.path
with np.load(vehicle_path) as data:
V = data["vector_data"]
X, idx = V[:, :44], V[:, 44].flatten()
np.set_printoptions(threshold=sys.maxsize)
for i in np.unique(idx):
_X = X[i == idx]
try:
numeric_key = features[arg]
if _X[:, numeric_key].sum() > 0:
print(_X[:, 0])
# print(X[:, numeric_key])
# print(X.shape)
# else:
# print(False)
# print(X[:, numeric_key])
# print(numeric_key)
except KeyError:
print(f"No feature named {arg} exists!")
def do_print_labels_for_scenario(self, arg: str):
with open("output/labeled_scenarios_vehicle_a.json") as labeled_scenarios:
labeled_scenarios = json.load(labeled_scenarios)
one_hot_encoding = labeled_scenarios[arg]
print(decode_one_hot_vector(one_hot_encoding, SCENARIO_LABEL_LIST))
def do_print_npz_direction(self, arg: str):
print(self.loaded_npz_trajectory.direction)
def do_get_bucket_similarities(self, arg: str):
vehicle_path = self.loaded_npz_trajectory.path.split("/")[-1]
with open("datasets/encoder_output_vehicle_a_mse.json") as encoder_output:
encoder_output_data = json.load(encoder_output)
with open("datasets/uae_buckets_cache.json") as uae_cache:
uae_cache_data = json.load(uae_cache)
cos_sim = torch.nn.CosineSimilarity(dim=0)
encoded_trajectory = encoder_output_data[vehicle_path]
bucket_keys = list(uae_cache_data.keys())
print(bucket_keys)
for key in bucket_keys:
print(
f"{key}: {cos_sim(torch.Tensor(uae_cache_data[key]), torch.Tensor(encoded_trajectory))}"
)
def do_create_bucket_similarities_dataset(self, arg: str):
with open("config.yml") as config:
config_data = yaml.safe_load(config)
npz_directory = config_data["npz_dataset"]
similarity_dataset = {}
vehicle_paths = list_vehicle_files_absolute(npz_directory)
with open("datasets/encoder_output_vehicle_a_mse.json") as encoder_output:
encoder_output_data = json.load(encoder_output)
with open("datasets/uae_buckets_cache.json") as uae_cache:
# Bucket order in cache:
# 0 Left
# 1 Right
# 2 Stationary
# 3 Straight
# 4 Straight-Left
# 5 Straight-Right
# 6 Right-U-Turn
# 7 Left-U-Turn
uae_cache_data = json.load(uae_cache)
cos_sim = torch.nn.CosineSimilarity(dim=0)
for i in tqdm(range(len(vehicle_paths))):
vehicle_path = vehicle_paths[i].split("/")[-1]
encoded_trajectory = encoder_output_data[vehicle_path]
bucket_keys = list(uae_cache_data.keys())
bucket_similarities = []
for key in bucket_keys:
bucket_similarities.append(
cos_sim(
torch.Tensor(uae_cache_data[key]),
torch.Tensor(encoded_trajectory),
).tolist()
)
similarity_dataset[vehicle_path] = bucket_similarities
with open("datasets/similarity_dataset.json", "w") as similarity_dataset_file:
json.dump(similarity_dataset, similarity_dataset_file)
def do_get_similarity_distribution_for_bucket(self, arg: str):
bucket_indeces = {
"Left": 0,
"Right": 1,
"Stationary": 2,
"Straight": 3,
"Straight-Left": 4,
"Straight-Right": 5,
"Right-U-Turn": 6,
"Left-U-Turn": 7,
}
bucket_index = bucket_indeces[arg]
with open("datasets/similarity_dataset.json") as sim_file:
sim_data = json.load(sim_file)
sim_data_keys = list(sim_data.keys())
with open("output/processed.json") as labeled_file:
labeled_data = json.load(labeled_file)
labeled_data_keys = list(labeled_data.keys())
print(len(labeled_data_keys))
filtered_keys = list(
filter(lambda x: labeled_data[x] == bucket_index, labeled_data_keys)
)
output = np.zeros(8)
for key in filtered_keys:
output += np.array(sim_data[key])
print(output / len(filtered_keys))
print(len(filtered_keys))
def do_get_bucket_similarities_softmax(self, arg: str):
vehicle_path = self.loaded_npz_trajectory.path.split("/")[-1]
with open("datasets/encoder_output_vehicle_a_mse.json") as encoder_output:
encoder_output_data = json.load(encoder_output)
with open("datasets/uae_buckets_cache.json") as uae_cache:
uae_cache_data = json.load(uae_cache)
cos_sim = torch.nn.CosineSimilarity(dim=0)
encoded_trajectory = encoder_output_data[vehicle_path]
bucket_keys = list(uae_cache_data.keys())
print(bucket_keys)
similarities = []
for key in bucket_keys:
similarity = cos_sim(
torch.Tensor(uae_cache_data[key]), torch.Tensor(encoded_trajectory)
)
print(f"{key}: {similarity}")
similarities.append(similarity)
softmax = torch.nn.Softmax()
print(softmax(torch.Tensor(similarities)))
def do_has_parking_lot(self, arg: str):
npz_trajectory = self.loaded_npz_trajectory
V = npz_trajectory.vector_data
X, idx = V[:, :44], V[:, 44].flatten()
for i in np.unique(idx):
_X = X[idx == i]
if _X[:, 13:16].sum() > 0:
print(_X[:, 0])
print(_X[:, 1])
def do_create_scenario_labeled_scenarios(self, arg: str):
vehicle_file_paths = list_vehicle_files_absolute(
directory="/storage_local/fzi_datasets_tmp/waymo_open_motion_dataset/unzipped/train-2e6/"
)
vectors = {
8: "vehicle",
9: "pedestrian",
10: "cyclist",
14: "freeway",
15: "surface_street",
16: "bike_lane",
30: "stop_sign",
31: "crosswalk",
32: "driveway",
}
# Other features
# Has parking lot
# vehicle_a_file_paths = [arg]
# write = True
# with open("output/labeled_scenarios_vehicle_a.json", "a") as file:
# file.write("{")
with open("output/labeled_scenarios_vehicle_b.json", "a") as file:
file.write("{")
for index in tqdm(range(len(vehicle_file_paths))):
label = ""
vehicle_file_path = vehicle_file_paths[index]
# if (
# vehicle_file_path.split("/")[-1]
# == "vehicle_a_76106_00000_6478343393.npz"
# ):
# write = True
# continue
# if write:
with np.load(vehicle_file_path) as vehicle_data:
X = vehicle_data["vector_data"][:, :45]
for vector in list(vectors.keys()):
if X[:, vector].sum() > 0:
label += vectors[vector] + " "
encoding = one_hot_encode_trajectory(
label,
[
"vehicle",
"pedestrian",
"cyclist",
"freeway",
"surface_street",
"bike_lane",
"stop_sign",
"crosswalk",
"driveway",
],
)
file.write(f'"{vehicle_file_path.split("/")[-1]}": {encoding},\n')
file.write("}")
def do_get_u_turn_candidates(self, arg: str):
with open("config.yml") as config:
config = yaml.safe_load(config)
npz_directory = config["npz_dataset"]
output = {}
trajectory_paths = list_vehicle_files_absolute(npz_directory)
for i in tqdm(range(len(trajectory_paths))):
path = trajectory_paths[i]
npz_trajectory = NpzTrajectory(path)
delta_angle = npz_trajectory.get_sum_of_delta_angles()
rel_displacement = npz_trajectory.get_relative_displacement()
if delta_angle > 130:
with open("output/potential_u_turns.txt", "a") as file:
file.write(
f"Path: {path}, Relative Displacement: {rel_displacement}\n"
)
def do_load_trajectory(self, arg: str):
"""Loads the trajectory specified by the loaded scenario and the given vehicle ID.
This trajectory can then be plotted and used in the CLI.
Args:
arg (str): The vehicle ID of the trajectory to load.
"""
if not self.scenario_loaded():
return
vehicle_id = arg.split()[0]
self.loaded_trajectory = Trajectory(
self.loaded_scenario, specific_id=vehicle_id
)
print(f"The trajectory for vehicle {vehicle_id} has successfully been loaded.")
def do_print_loaded_trajectory_coordinates(self, arg: str):
"""Prints the splined coordinates of the loaded trajectory.
Args:
arg (str): No arguments required.
"""
print(self.loaded_trajectory.splined_coordinates)
def do_print_loaded_ego_coordinates(self, arg: str):
"""Prints the ego coordinates using the static method in the Trajectory class for coordinate parsing.
Args:
arg (str): No arguments required.
"""
(
rotated_coordinates,
rotated_angle,
original_starting_x,
original_starting_y,
) = Trajectory.get_rotated_ego_coordinates_from_coordinates(
self.loaded_trajectory.splined_coordinates
)
unrotated_coordinates = Trajectory.get_coordinates_from_rotated_ego_coordinates(
rotated_coordinates, rotated_angle, original_starting_x, original_starting_y
)
print(unrotated_coordinates)
def do_print_current_raw_scenario(self, arg: str):
"""Prints the current scenario that has been loaded in its decoded form.
This function is for debugging purposes only.
"""
print(self.loaded_scenario.data)
def do_print_roadgraph(self, arg: str):
"""Prints the roadgraph of the loaded scenario."""
pass
# print(self.loaded_scenario.data["roadgraph"])
def do_animate_scenario(self, arg: str):
"""Plots the scenario that has previously been
loaded with the 'load_scenario' command.
Args:
arg (str): No arguments are required.
"""
# Load config file
with open("config.yml", "r") as file:
config = yaml.safe_load(file)
output_folder = config["output_folder"]
parser = self.arg_parser()
args = parser.parse_args(arg.split())
if self.loaded_scenario is not None:
anim = self.loaded_scenario.get_animation(args.ids)
anim.save(
f"/home/pmueller/llama_traffic/output/{self.loaded_scenario.name}.mp4",
writer="ffmpeg",
fps=10,
)
print(
f"Successfully created animation in {output_folder}{self.loaded_scenario.name}.mp4!\n"
)
else:
print(
(
"\nNo scenario has been initialized yet!"
" \nPlease use 'load_scenario'"
" to load a scenario before calling"
" the 'plot_scenario' command.\n"
)
)
return
def do_print_bert_similarity_to_word(self, arg: str):
"""Returns the cosine similarity between the given text input and the
different direction buckets.
Args:
arg (str): The text input for which to get the similarity.
"""
# Check for empty arguments (no text input provided)
if arg == "":
print(
(
"\nYou have provided no text input for which to get the similarity.\nPlease provide a text input!\n"
)