File size: 57,690 Bytes
3e56913
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
"""
Code that loads the dataset for training.
partially taken from https://github.com/autonomousvision/carla_garage/blob/main/team_code/data.py
(MIT licence)
"""
import datetime
import glob
import gzip
import json
import os
import pickle as pkl
import random
import sys
from pathlib import Path
from typing import Any

import numpy as np
import cv2
import torch
import ujson
from hydra.utils import get_original_cwd
import utils.numpy_compat  # noqa: F401  (imgaug/numpy2 shim, must precede imgaug)
from imgaug import augmenters as ia
from PIL import Image, ImageDraw
from scipy.interpolate import interp1d
from torch.utils.data import Dataset

from utils.image_enhancing import histogram_equalization
from utils.logging_project import rank_zero_print, rank_zero_tqdm
from utils.navigation_text import format_target_waypoint_text
from utils.projection import project_points

VIZ_DATA = False


def normalize_angle(angle):
    return (angle + np.pi) % (2 * np.pi) - np.pi

class BaseDataset(Dataset):  # pylint: disable=locally-disabled, invalid-name
    """
    Base class for the dataset.
    """

    def __init__(self,
            base = False,
            dreamer = False,
            **cfg,
        ):
        for key, value in cfg.items():
            setattr(self, key, value)

        self.dreamer = dreamer

        self.tfs = image_augmenter(prob=self.img_augmentation_prob)

        filter_infractions_per_route = True

        self.rgb_folder = 'rgb'
        self.dreamer_folder = 'dreamer'
        
        self.images = []
        self.boxes = []
        self.measurements = []
        self.sample_start = []
        self.augment_exists = []
        self.alternative_trajectories = []

        self.temporal_measurements = []

        total_routes = 0
        perfect_routes = 0
        crashed_routes = 0

        fail_reasons = {}

        repo_path = get_original_cwd()
        
        augment_exist = False



        if not self.bucket_name == "all":
            with open(f"{repo_path}/" + self.bucket_path + '/buckets_paths.pkl', 'rb') as f:
                bucket_dict = pkl.load(f)

            bucket_run_ids = None

            # TODO: this is stupid that its manual, should change bucket names to match the saved dict with pathes
            if self.bucket_name == "all":
                pass
            elif self.bucket_name == 'acceleration_negative_5':
                bucket_run_ids = bucket_dict['acceleration_-5']# + bucket_dict['acceleration_-20'] + bucket_dict['acceleration_-40']
            elif self.bucket_name == "acceleration_negative_1":
                bucket_run_ids = bucket_dict['acceleration_-1']
            elif self.bucket_name == "acceleration_positive_1":
                bucket_run_ids = bucket_dict['acceleration_5']
            elif self.bucket_name == "acceleration_positive_5":
                bucket_run_ids = bucket_dict['acceleration_20']# + bucket_dict['acceleration_40'] + bucket_dict['acceleration_1000000']
            elif self.bucket_name == "lateral_control_1":
                bucket_run_ids = bucket_dict['lateral_control_1']
            elif self.bucket_name == "lateral_control_1_2":
                bucket_run_ids = bucket_dict['lateral_control_1'] + bucket_dict['lateral_control_2']
            elif self.bucket_name == "lateral_control_high":
                bucket_run_ids = bucket_dict['lateral_control_2'] + bucket_dict['lateral_control_5'] + bucket_dict['lateral_control_1000000']
            elif self.bucket_name == "lateral_control_higher_5":
                bucket_run_ids = bucket_dict['lateral_control_5'] + bucket_dict['lateral_control_1000000']
            elif self.bucket_name == "recovery":
                bucket_run_ids = bucket_dict['recovery_data_small'] + bucket_dict['recovery_data_large']
            else:
                if self.bucket_name not in bucket_dict:
                    raise ValueError(f"Bucket name {self.bucket_name} not found.")
                bucket_run_ids = bucket_dict[self.bucket_name]

            run_id_dict = {}
            if bucket_run_ids is not None:
                for run_id in bucket_run_ids:
                    run_id = run_id.replace('database/simlingo_v2_2025_01_10', self.bucket_path)
                    run_id_path = Path(run_id)
                    run_id_parent = run_id_path.parent
                    run_id_name = run_id_path.name
                    run_id_absolut = str(run_id_parent)
                    run_id_absolut = f"{repo_path}/{str(run_id_parent)}"
                    if run_id_absolut not in run_id_dict:
                        run_id_dict[run_id_absolut] = [run_id_name]
                    else:
                        run_id_dict[run_id_absolut].append(run_id_name)


        mixed_index_path = getattr(self, "mixed_index_path", None)
        extra_data_path = getattr(self, "extra_data_path", None)
        if mixed_index_path:
            with open(mixed_index_path, "r", encoding="utf-8") as handle:
                mixed_index = json.load(handle)
            route_dirs = []
            for group in ("legacy_routes", "multiview_routes"):
                for item in mixed_index.get(group, []):
                    route_dirs.append(item["route_dir"])
            rank_zero_print(
                f'Found {len(route_dirs)} routes from mixed index {mixed_index_path}'
            )
        else:
            route_dirs = glob.glob(f"{repo_path}/" + self.data_path + '/data/simlingo/*/*/*/Town*')
            if extra_data_path:
                extra_dirs = glob.glob(
                    f"{repo_path}/" + extra_data_path + '/data/simlingo/*/*/*/Town*'
                )
                route_dirs.extend(extra_dirs)
                rank_zero_print(
                    f'Found {len(extra_dirs)} extra multi-view routes in {extra_data_path}'
                )
            rank_zero_print(f'Found {len(route_dirs)} routes in {f"{repo_path}/" + self.data_path}')
        
        if not self.use_old_towns:
            route_dirs = [route_dir for route_dir in route_dirs if 'lb1_split' not in route_dir]
            rank_zero_print(f'Found {len(route_dirs)} routes in {f"{repo_path}/" + self.data_path} after filtering out old towns')
        elif self.bucket_name == "old_towns":
            route_dirs = [route_dir for route_dir in route_dirs if 'lb1_split' in route_dir]
            rank_zero_print(f'Found {len(route_dirs)} routes in {f"{repo_path}/" + self.data_path} after filtering out non old towns')
        

        random.shuffle(route_dirs)
        split_percentage = 0.99
        if dreamer:
            # dreamer labels exist for the official training towns; keep the
            # same split convention as SimLingo (train: routes_training)
            if self.split == "train":
                route_dirs = [route_dir for route_dir in route_dirs if 'routes_training' in route_dir]
            elif self.split == "val":
                route_dirs = [route_dir for route_dir in route_dirs if 'routes_validation' in route_dir]
                route_dirs = route_dirs[:int(0.02 * len(route_dirs))]
        elif not self.use_town13:
            # split the data into official training(Town12 and old Towns) and validation set (Town13)
            if self.split == "train":
                route_dirs = [route_dir for route_dir in route_dirs if 'routes_training' in route_dir]
            elif self.split == "val":
                route_dirs = [route_dir for route_dir in route_dirs if 'routes_validation' in route_dir]
                route_dirs = route_dirs[:int(0.02 * len(route_dirs))]
        else:
            # use all towns
            if self.split == "train":
                route_dirs = route_dirs[:int(split_percentage * len(route_dirs))]
            elif self.split == "val":
                route_dirs = route_dirs[int(split_percentage * len(route_dirs)):]
        
        total_routes += len(route_dirs)
        rank_zero_print(f'Use {len(route_dirs)} routes.')
        
        for sub_root in rank_zero_tqdm(route_dirs, file=sys.stdout):

            route_dir = sub_root # + '/' + route

            if dreamer:
                dreamer_route_dir = route_dir.replace('/data/simlingo', f'/{self.dreamer_folder}/simlingo')
                if not os.path.exists(dreamer_route_dir):
                    if "no_dreamer_dir" not in fail_reasons:
                        fail_reasons["no_dreamer_dir"] = 1
                    else:
                        fail_reasons["no_dreamer_dir"] += 1
                    continue

            if filter_infractions_per_route:
                if not os.path.isfile(route_dir + '/results.json.gz'):
                    total_routes += 1
                    crashed_routes += 1
                    if "no_results.json" not in fail_reasons:
                        fail_reasons["no_results.json"] = 1
                    else:
                        fail_reasons["no_results.json"] += 1
                    continue

                with gzip.open(route_dir + '/results.json.gz', 'rt') as f:
                    total_routes += 1
                    try:
                        results_route = ujson.load(f)
                    except Exception as e:
                        rank_zero_print(f"Error in {route_dir}")
                        rank_zero_print(e)
                        if "results.json_load_error" not in fail_reasons:
                            fail_reasons["results.json_load_error"] = 1
                        else:
                            fail_reasons["results.json_load_error"] += 1
                        continue

                if results_route['scores']['score_composed'] < 100.0:  # we also count imperfect runs as failed (except minspeedinfractions)
                    cond1 = results_route['scores']['score_route'] > 94.0  # we allow 6% of the route score to be missing
                    cond2 = results_route['num_infractions'] == (len(results_route['infractions']['min_speed_infractions']) + len(results_route['infractions']['outside_route_lanes']))
                    if not (cond1 and cond2):  # if the only problem is minspeedinfractions, keep it
                        crashed_routes += 1
                        if "route_crashed" not in fail_reasons:
                            fail_reasons["route_crashed"] = 1
                        else:
                            fail_reasons["route_crashed"] += 1
                        continue

            perfect_routes += 1

            if not os.path.exists(route_dir + f'/{self.rgb_folder}'):
                if "no_rgb_folder" not in fail_reasons:
                    fail_reasons["no_rgb_folder"] = 1
                else:
                    fail_reasons["no_rgb_folder"] += 1
                continue

            num_seq = len(os.listdir(route_dir + f'/{self.rgb_folder}'))

            for seq in range(self.skip_first_n_frames, num_seq - self.pred_len - self.hist_len - 1):
                image = []
                box = []
                measurement = []
                augment_exist = False

                measurement_file = route_dir + '/measurements' + f'/{(seq + self.hist_len-1):04}.json.gz'

                if dreamer:
                    dreamer_file_path = dreamer_route_dir + f'/{self.dreamer_folder}' + f'/{(seq + self.hist_len-1):04}.json.gz'
                    if not os.path.exists(dreamer_file_path):
                        if "no_dreamer_file" not in fail_reasons:
                            fail_reasons["no_dreamer_file"] = 1
                        else:
                            fail_reasons["no_dreamer_file"] += 1
                        continue

                if self.bucket_name is not None and self.bucket_name != "all":
                    measurement_file_path = Path(measurement_file)
                    if str(measurement_file_path.parent) in run_id_dict:
                        if measurement_file_path.name not in run_id_dict[str(measurement_file_path.parent)]:
                            if "measurement_file_not_in_bucket" not in fail_reasons:
                                fail_reasons["measurement_file_not_in_bucket"] = 1
                            else:
                                fail_reasons["measurement_file_not_in_bucket"] += 1
                            continue
                    else:
                        if "measurement_folder_not_in_bucket" not in fail_reasons:
                            fail_reasons["measurement_folder_not_in_bucket"] = 1
                        else:
                            fail_reasons["measurement_folder_not_in_bucket"] += 1
                        continue

                # Loads the current (and past) frames (if seq_len > 1)
                skip = False
                augment_exist = True
                for idx in range(self.hist_len):
                    image.append(route_dir +  f'/{self.rgb_folder}' + (f'/{(seq + idx):04}.jpg'))
                    box.append(route_dir + '/boxes' + (f'/{(seq + idx):04}.json.gz'))

                if skip:
                    if "file_not_found" not in fail_reasons:
                        fail_reasons["file_not_found"] = 1
                    else:
                        fail_reasons["file_not_found"] += 1
                    continue

                measurement.append(route_dir + '/measurements')

                self.images.append(image)
                self.boxes.append(box)
                self.measurements.append(measurement)
                self.sample_start.append(seq)
                self.augment_exists.append(augment_exist)
                if dreamer:
                    self.alternative_trajectories.append(dreamer_file_path)

        # There is a complex "memory leak"/performance issue when using Python
        # objects like lists in a Dataloader that is loaded with
        # multiprocessing, num_workers > 0
        # A summary of that ongoing discussion can be found here
        # https://github.com/pytorch/pytorch/issues/13246#issuecomment-905703662
        # A workaround is to store the string lists as numpy byte objects
        # because they only have 1 refcount.
        self.images = np.array(self.images).astype(np.string_)
        self.boxes = np.array(self.boxes).astype(np.string_)
        self.measurements = np.array(self.measurements).astype(np.string_)
        if dreamer:
            self.alternative_trajectories = np.array(self.alternative_trajectories).astype(np.string_)

        self.sample_start = np.array(self.sample_start)
        # if rank == 0:
        rank_zero_print(f'[{self.split} samples]: Loading {len(self.images)} images from {self.data_path} for bucket {self.bucket_name}')
        rank_zero_print('Total amount of routes:', total_routes)
        rank_zero_print('Crashed routes:', crashed_routes)
        rank_zero_print('Perfect routes:', perfect_routes)
        rank_zero_print('Fail reasons:', fail_reasons)

    def __len__(self):
        """Returns the length of the dataset. """
        return self.images.shape[0]
    

    def load_current_and_future_measurements(self, measurements, sample_start):
        loaded_measurements = []

        ######################################################
        ######## load current and future measurements ########
        ######################################################

        # Since we load measurements for future time steps, we load and store them separately
        for i in range(self.hist_len):
            measurement_file = str(measurements[0], encoding='utf-8') + (f'/{(sample_start + i):04}.json.gz')

            with gzip.open(measurement_file, 'rt') as f1:
                measurements_i = ujson.load(f1)
            loaded_measurements.append(measurements_i)

        end = self.pred_len + self.hist_len
        start = self.hist_len

        for i in range(start, end):
            try:
                measurement_file = str(measurements[0], encoding='utf-8') + (f'/{(sample_start + i):04}.json.gz')

                with gzip.open(measurement_file, 'rt') as f1:
                    measurements_i = ujson.load(f1)
                loaded_measurements.append(measurements_i)
            except FileNotFoundError:
                # If the file is not found, we just use the last available measurement
                print(f"File not found: {measurement_file}")
                loaded_measurements.append(loaded_measurements[-1])
        current_measurement = loaded_measurements[self.hist_len - 1]
        measurement_file_current = str(measurements[0], encoding='utf-8') + (f'/{(sample_start + start-1):04}.json.gz')
        return loaded_measurements, current_measurement, measurement_file_current

    def load_waypoints(self, data, loaded_measurements, aug_translation=0.0, aug_rotation=0.0):

        waypoints = self.get_waypoints(loaded_measurements[self.hist_len - 1:],
                                                                        y_augmentation=aug_translation,
                                                                        yaw_augmentation=aug_rotation)
        data['waypoints'] = np.array(waypoints[1:-1])

        waypoints_org = self.get_waypoints(loaded_measurements[self.hist_len - 1:],
                                                                        y_augmentation=0,
                                                                        yaw_augmentation=0)
        data['waypoints_org'] = np.array(waypoints_org[1:-1])

        # 1D waypoints: only consider distance between waypoints
        waypoints_1d = [np.linalg.norm(waypoints_org[i+1] - waypoints_org[i]) for i in range(len(waypoints_org)-1)]
        # cumsum to get the distance from the start
        waypoints_1d = np.cumsum(waypoints_1d)
        waypoints_1d = [[x, 0] for x in waypoints_1d]
        data['waypoints_1d'] = np.array(waypoints_1d[:-1]).reshape(-1, 2)

        waypoints = [np.array([[1, 0, 0, x], [0, 1, 0, y], [0, 0, 1, 0], [0, 0, 0, 1]]) for x, y in waypoints]
        data['ego_waypoints'] = np.array(waypoints[:-1])
        
        waypoints_org = [np.array([[1, 0, 0, x], [0, 1, 0, y], [0, 0, 1, 0], [0, 0, 0, 1]]) for x, y in waypoints_org]
        data['ego_waypoints_org'] = np.array(waypoints_org[:-1])

        return data

    def load_plan_consequence_targets(
        self,
        data,
        loaded_measurements,
        box_paths,
        aug_translation=0.0,
        aug_rotation=0.0,
        load_future_boxes=False,
    ):
        """Load future actor geometry and conservative GT-path risk labels.

        Box files are optional in existing DriveVLA exports.  Missing files are
        never interpreted as an empty scene: geometry/clearance stay invalid,
        while explicit future vehicle/walker hazard fields can still supervise
        binary risk on the GT path.
        """
        horizon = 10
        max_obstacles = int(getattr(self, "consequence_max_obstacles", 32))
        max_clearance = float(getattr(self, "consequence_max_clearance", 20.0))
        ego_radius = float(getattr(self, "consequence_ego_radius", 0.9))

        obstacles = np.zeros((horizon, max_obstacles, 5), dtype=np.float32)
        obstacle_valid = np.zeros((horizon, max_obstacles), dtype=np.bool_)
        obstacle_step_valid = np.zeros(horizon, dtype=np.bool_)
        risk_target = np.zeros(horizon, dtype=np.float32)
        risk_valid = np.zeros(horizon, dtype=np.bool_)
        clearance_target = np.zeros(horizon, dtype=np.float32)
        clearance_valid = np.zeros(horizon, dtype=np.bool_)

        current_measurement = loaded_measurements[self.hist_len - 1]
        current_box_path = str(box_paths[-1], encoding="utf-8")
        current_frame = int(Path(current_box_path).name.split(".")[0])
        boxes_dir = Path(current_box_path).parent
        gt_path = np.asarray(data["waypoints"], dtype=np.float32)[:horizon]

        # Prefer the offline box cache when configured; it stores world-frame
        # boxes per route so no per-sample gzip probing is needed.
        box_cache = self._get_consequence_box_cache()
        cache_route_key = None
        cache_current_matrix = None
        if box_cache is not None:
            from dataloader.future_cache import canonical_route_id, route_hash

            cache_route_key = route_hash(canonical_route_id(current_box_path))
            matrix = np.asarray(current_measurement.get("ego_matrix"))
            if matrix.shape == (4, 4):
                cache_current_matrix = matrix

        future_measurements = loaded_measurements[
            self.hist_len:self.hist_len + horizon
        ]
        for step in range(min(horizon, len(future_measurements))):
            measurement = future_measurements[step]
            hazard_keys = ("vehicle_hazard", "walker_hazard")
            available = [key for key in hazard_keys if key in measurement]
            if available:
                risk_target[step] = float(
                    any(self._as_hazard_bool(measurement[key]) for key in available)
                )
                risk_valid[step] = True

            if box_cache is not None:
                if cache_current_matrix is None:
                    continue
                entry = box_cache.get(cache_route_key, current_frame + step + 1)
                if entry is None:
                    continue
                transformed = self._cached_boxes_in_current_frame(
                    entry[0],
                    entry[1],
                    current_matrix=cache_current_matrix,
                    aug_translation=aug_translation,
                    aug_rotation=aug_rotation,
                )
            elif load_future_boxes:
                future_box_path = boxes_dir / f"{current_frame + step + 1:04}.json.gz"
                if not future_box_path.is_file():
                    continue
                try:
                    with gzip.open(future_box_path, "rt") as box_file:
                        future_boxes = ujson.load(box_file)
                except (OSError, ValueError, ujson.JSONDecodeError):
                    continue
                if isinstance(future_boxes, dict):
                    future_boxes = future_boxes.get(
                        "boxes", future_boxes.get("bounding_boxes")
                    )
                if not isinstance(future_boxes, list):
                    continue
                transformed = []
                for box in future_boxes:
                    parsed = self._future_box_in_current_frame(
                        box,
                        current_measurement=current_measurement,
                        future_measurement=measurement,
                        aug_translation=aug_translation,
                        aug_rotation=aug_rotation,
                    )
                    if parsed is not None:
                        transformed.append(parsed)
            else:
                continue

            obstacle_step_valid[step] = True
            transformed.sort(key=lambda item: float(np.linalg.norm(item[:2])))
            transformed = transformed[:max_obstacles]
            if transformed:
                count = len(transformed)
                obstacles[step, :count] = np.asarray(transformed, dtype=np.float32)
                obstacle_valid[step, :count] = True

            if step < len(gt_path):
                risk, clearance = self._point_box_consequence(
                    gt_path[step],
                    obstacles[step],
                    obstacle_valid[step],
                    ego_radius=ego_radius,
                    max_clearance=max_clearance,
                )
                risk_target[step] = risk
                risk_valid[step] = True
                clearance_target[step] = clearance
                clearance_valid[step] = True

        data["consequence_risk_target"] = risk_target
        data["consequence_risk_valid"] = risk_valid
        data["consequence_clearance_target"] = clearance_target
        data["consequence_clearance_valid"] = clearance_valid
        data["future_obstacles"] = obstacles
        data["future_obstacle_valid"] = obstacle_valid
        data["future_obstacle_step_valid"] = obstacle_step_valid
        return data

    def load_objects(self, data, box_paths, aug_translation=0.0, aug_rotation=0.0, relation_valid=True):
        """Attach the precomputed object-bank tokens of the current frame (scripts/build_object_bank.py).

        Fixed-size rows: data['objects'] [N, FEAT_DIM] float32, data['object_mask'] [N] bool and
        data['object_relation'] [N] int64 (-100 where unlabelled). A missing bank file yields an empty
        bank rather than an error so partially built caches still train.
        """
        from dataloader.object_bank import FEAT_DIM, RELATION_PAD, augment_raw, raw_to_features

        max_objects = int(getattr(self, "object_bank_max_objects", 32))
        folder = getattr(self, "object_bank_folder", "object_bank")
        current_box_path = Path(str(box_paths[-1], encoding="utf-8"))
        frame = int(current_box_path.name.split(".")[0])
        route_dir = str(current_box_path.parents[1])
        bank_path = Path(route_dir.replace("/data/simlingo/", f"/{folder}/simlingo/")) / "objects.npz"

        objects = np.zeros((max_objects, FEAT_DIM), dtype=np.float32)
        mask = np.zeros(max_objects, dtype=np.bool_)
        relation = np.full(max_objects, RELATION_PAD, dtype=np.int64)
        cache = getattr(self, "_object_bank_cache", None)
        if cache is None or cache[0] != bank_path:
            if bank_path.is_file():
                with np.load(bank_path) as handle:
                    cache = (bank_path, handle["raw"], handle["relation"], handle["count"])
            else:
                cache = (bank_path, None, None, None)
            self._object_bank_cache = cache
        _, raw_all, rel_all, count_all = cache
        if raw_all is not None and frame < len(raw_all):
            count = min(int(count_all[frame]), max_objects, raw_all.shape[1])
            if count > 0:
                raw = augment_raw(raw_all[frame, :count].astype(np.float32), aug_translation, aug_rotation)
                objects[:count] = raw_to_features(raw)
                mask[:count] = True
                if relation_valid:
                    relation[:count] = rel_all[frame, :count].astype(np.int64)
        data["objects"] = objects
        data["object_mask"] = mask
        data["object_relation"] = relation
        return data

    @staticmethod
    def _as_hazard_bool(value):
        if isinstance(value, (list, tuple, np.ndarray)):
            return any(bool(item) for item in value)
        return bool(value)

    def _get_consequence_box_cache(self):
        """Lazy per-process handle; workers fork after dataset construction."""
        root = getattr(self, "consequence_box_cache_root", None)
        if not root:
            return None
        cache = getattr(self, "_consequence_box_cache", None)
        if cache is None:
            from dataloader.consequence_box_cache import ConsequenceBoxCache

            cache = ConsequenceBoxCache(root)
            self._consequence_box_cache = cache
        return cache

    def _cached_boxes_in_current_frame(
        self,
        world_boxes,
        box_valid,
        current_matrix,
        aug_translation,
        aug_rotation,
    ):
        """Move cached world-frame boxes into the (augmented) current ego frame.

        Mirrors `_future_box_in_current_frame` exactly, minus the future-frame
        hop which the cache already applied at build time.
        """
        rows = np.asarray(world_boxes, dtype=np.float64)[np.asarray(box_valid, dtype=bool)]
        if rows.size == 0:
            return []
        rotation = current_matrix[:3, :3]
        translation = current_matrix[:3, 3]
        # (p - t) @ R equals R.T @ (p - t) applied row-wise.
        positions = (rows[:, :3] - translation) @ rotation
        positions_aug = self.augment_route(
            positions[:, :2],
            y_augmentation=aug_translation,
            yaw_augmentation=aug_rotation,
        )
        current_yaw = np.arctan2(current_matrix[1, 0], current_matrix[0, 0])
        relative_yaw = normalize_angle(
            rows[:, 5] - current_yaw - np.deg2rad(aug_rotation)
        )
        stacked = np.column_stack((
            np.asarray(positions_aug)[:, 0],
            np.asarray(positions_aug)[:, 1],
            rows[:, 3],
            rows[:, 4],
            relative_yaw,
        )).astype(np.float32)
        return list(stacked)

    def _future_box_in_current_frame(
        self,
        box,
        current_measurement,
        future_measurement,
        aug_translation,
        aug_rotation,
    ):
        physical_classes = {"car", "walker", "static", "static_car"}
        if (
            not isinstance(box, dict)
            or box.get("class") not in physical_classes
            or "position" not in box
            or "extent" not in box
        ):
            return None
        position = np.asarray(box["position"], dtype=np.float64)
        extent = np.asarray(box["extent"], dtype=np.float64)
        if position.size < 2 or extent.size < 2:
            return None
        if not np.isfinite(position[:2]).all() or not np.isfinite(extent[:2]).all():
            return None

        current_matrix = np.asarray(current_measurement.get("ego_matrix"))
        future_matrix = np.asarray(future_measurement.get("ego_matrix"))
        if current_matrix.shape != (4, 4) or future_matrix.shape != (4, 4):
            return None
        position_3d = np.zeros(3, dtype=np.float64)
        position_3d[:min(3, position.size)] = position[:3]
        world_position = (
            future_matrix[:3, :3] @ position_3d + future_matrix[:3, 3]
        )
        current_position = current_matrix[:3, :3].T @ (
            world_position - current_matrix[:3, 3]
        )
        position_aug = self.augment_route(
            current_position[None, :2],
            y_augmentation=aug_translation,
            yaw_augmentation=aug_rotation,
        )[0]

        current_yaw = np.arctan2(current_matrix[1, 0], current_matrix[0, 0])
        future_yaw = np.arctan2(future_matrix[1, 0], future_matrix[0, 0])
        relative_yaw = normalize_angle(
            future_yaw + float(box.get("yaw", 0.0))
            - current_yaw - np.deg2rad(aug_rotation)
        )
        return np.array(
            [
                position_aug[0],
                position_aug[1],
                max(float(extent[0]), 0.0),
                max(float(extent[1]), 0.0),
                relative_yaw,
            ],
            dtype=np.float32,
        )

    @staticmethod
    def _point_box_consequence(
        point,
        boxes,
        box_valid,
        ego_radius,
        max_clearance,
    ):
        valid_boxes = boxes[box_valid]
        if len(valid_boxes) == 0:
            return 0.0, float(max_clearance)
        delta = np.asarray(point)[None, :2] - valid_boxes[:, :2]
        yaw = valid_boxes[:, 4]
        local_x = np.cos(yaw) * delta[:, 0] + np.sin(yaw) * delta[:, 1]
        local_y = -np.sin(yaw) * delta[:, 0] + np.cos(yaw) * delta[:, 1]
        local = np.stack((local_x, local_y), axis=-1)
        q = np.abs(local) - np.maximum(valid_boxes[:, 2:4], 0.0)
        outside = np.linalg.norm(np.maximum(q, 0.0), axis=-1)
        inside = np.minimum(np.max(q, axis=-1), 0.0)
        clearance = float(np.min(outside + inside - ego_radius))
        clearance = float(np.clip(clearance, -max_clearance, max_clearance))
        return float(clearance <= 0.0), clearance
    
    def load_route(self, data, current_measurement, aug_translation=0.0, aug_rotation=0.0):
        route = current_measurement['route_original']
        route = self.augment_route(route, y_augmentation=aug_translation, yaw_augmentation=aug_rotation)

        route_adjusted = np.array(current_measurement['route'])
        route_adjusted_org = self.augment_route(route_adjusted, y_augmentation=0, yaw_augmentation=0)
        route_adjusted = self.augment_route(route_adjusted, y_augmentation=aug_translation, yaw_augmentation=aug_rotation)
        if len(route) < self.num_route_points:
            num_missing = self.num_route_points - len(route)
            route = np.array(route)
            # Fill the empty spots by repeating the last point.
            route = np.vstack((route, np.tile(route[-1], (num_missing, 1))))
        else:
            route = np.array(route[:self.num_route_points])
            
        route_adjusted = self.equal_spacing_route(route_adjusted)
        route_adjusted_org = self.equal_spacing_route(route_adjusted_org)
        route = self.equal_spacing_route(route)
        
        data['route'] = route
        data['route_adjusted_org'] = route_adjusted_org
        data['route_adjusted'] = route_adjusted

        return data
    
    def load_images(self, data, images, augment_sample=False):
        loaded_images = []
        for i in range(self.hist_len):
            images_path = str(images[i], encoding='utf-8')
            if augment_sample:
                images_path = images_path.replace('rgb', 'rgb_augmented')

            if not os.path.isfile(images_path):
                print(f"File not found: {images_path}")
                raise FileNotFoundError

            images_i = cv2.imread(images_path, cv2.IMREAD_COLOR)
            images_i = cv2.cvtColor(images_i, cv2.COLOR_BGR2RGB)
            if self.image_enhancing:
                images_i = histogram_equalization(images_i)

            if self.img_augmentation:
                images_i = self.tfs(image=images_i)

            if self.cut_bottom_quarter or self.img_shift_augmentation:
                images_i = images_i[:int(images_i.shape[0] - (images_i.shape[0] * 4.8) // 16), :, :]

            loaded_images.append(images_i)

        processed_image = np.asarray(loaded_images)
        processed_image = np.transpose(processed_image, (0, 3, 1, 2)) # (T, C, H, W)
        processed_image = np.expand_dims(processed_image, axis=1) # T, N, C, H, W

        view_mask = np.array([1, 0, 0], dtype=np.int64)
        if getattr(self, "load_side_cameras", False) and not augment_sample:
            current_front = str(images[self.hist_len - 1], encoding="utf-8")
            extra_frames = []
            for idx, folder in enumerate(("rgb_left", "rgb_right"), start=1):
                side_path = current_front.replace("/rgb/", f"/{folder}/")
                if side_path == current_front or not os.path.isfile(side_path):
                    continue
                side_image = cv2.imread(side_path, cv2.IMREAD_COLOR)
                side_image = cv2.cvtColor(side_image, cv2.COLOR_BGR2RGB)
                if self.image_enhancing:
                    side_image = histogram_equalization(side_image)
                if self.cut_bottom_quarter or self.img_shift_augmentation:
                    side_image = side_image[:int(side_image.shape[0] - (side_image.shape[0] * 4.8) // 16), :, :]
                extra_frames.append(np.transpose(side_image, (2, 0, 1))[None, None])
                view_mask[idx] = 1
            if extra_frames:
                extra = np.concatenate(extra_frames, axis=0)
                processed_image = np.concatenate([processed_image, extra], axis=0)

        data['rgb'] = processed_image
        data['view_mask'] = view_mask

        return data

    def run_image_processor(self, data):
        """
        Run the HF image/video processor in the dataloader worker (parallel)
        instead of collate_fn (main process). Requires self._processor to be
        injected by the DataModule.
        """
        encoder = getattr(self, 'encoder', None)
        processor = getattr(self, '_processor', None)
        if processor is None:
            return data

        rgb = data['rgb']  # [T, N, C, H, W]
        if encoder == 'qwen2_5_vl':
            T, N, C, H, W = rgb.shape
            images_list = []
            for t in range(T):
                for n in range(N):
                    img = np.transpose(rgb[t, n], (1, 2, 0))  # HWC
                    if img.dtype != np.uint8:
                        img = np.clip(img, 0, 255).astype(np.uint8)
                    images_list.append(img)
            processed = processor.image_processor(images_list, return_tensors="pt")
            data['pixel_values'] = processed['pixel_values']
            data['image_grid_thw'] = processed['image_grid_thw']  # [T*N, 3]
        elif encoder == 'qwen3_vl':
            # native video mode: the T front-camera frames form one video clip
            frames = rgb[:, 0]  # [T, C, H, W]
            if frames.dtype != np.uint8:
                frames = np.clip(frames, 0, 255).astype(np.uint8)
            video = torch.from_numpy(np.ascontiguousarray(frames))
            processed = processor.video_processor(
                videos=[video],
                do_sample_frames=False,
                return_tensors="pt",
            )
            data['pixel_values'] = processed['pixel_values_videos']
            data['image_grid_thw'] = processed['video_grid_thw'].reshape(-1)  # [3]
        return data

    def set_navigational_outputs(self, data, current_measurement, target_point, next_target_point):
        """Fill data['map_route'] / data['navigation_command'] according to route_as."""
        if self.route_as == 'coords':
            data['map_route'] = data['route'][:20]
            data['navigation_command'] = ""
        elif self.route_as == 'target_point':
            data['map_route'] = np.array([target_point, next_target_point])
            data['navigation_command'] = ""
        elif self.route_as in ('command', 'command_tp'):
            command_options, _ = self.get_navigational_conditioning(
                data,
                current_measurement,
                target_point,
                next_target_point,
            )
            data['navigation_command'] = command_options[0]
            if self.route_as == 'command_tp':
                if getattr(self, 'command_tp_text', False):
                    data['navigation_command'] += format_target_waypoint_text(
                        target_point, next_target_point
                    )
                # get_navigational_conditioning already sets data['map_route'] to the two TPs
                data['map_route'] = np.array(data['map_route'], dtype=np.float32)
            else:
                data['map_route'] = np.zeros((2, 2), dtype=np.float32)
        else:
            raise ValueError(f"Unknown route_as: {self.route_as}")
        return data

    def get_navigational_conditioning(self, data, current_measurement, target_point, next_target_point):
        placeholder_values = {}
        target_options = []
                
        tp = [target_point, next_target_point]
        tp = np.array(tp)
        data['map_route'] = tp
        data['target_points'] = tp
        target_point1_round = np.round(data['target_points'][0], 2).tolist()
        target_point2_round = np.round(data['target_points'][1], 2).tolist()

        if 'target_point' in self.route_as:
            if 'target_point_language' in self.route_as:
                target_options.append(f"Target waypoint: 1:{target_point1_round} 2:{target_point2_round}")
            else:
                target_options.append(f"Target waypoint: <TARGET_POINT><TARGET_POINT>.")
                placeholder_values = {'<TARGET_POINT>': data['target_points']}
        if 'command' in self.route_as:
            # get distance from target_point
            dist_to_command = np.linalg.norm(target_point)
            dist_to_command = int(dist_to_command)
            map_command = {
                1: 'go left at the next intersection',
                2: 'go right at the next intersection',
                3: 'go straight at the next intersection',
                4: 'follow the road',
                5: 'do a lane change to the left',
                6: 'do a lane change to the right',        
            }
            command_template_mappings = {
                1: [0, 2, 4, 7],
                2: [1, 3, 5, 8],
                3: [6, 9],
                4: [38, 40, 42, 43, 44, 45],
                5: [34, 36],
                6: [35, 37],
            }
            command = map_command[current_measurement["command"]]
            next_command = map_command[current_measurement["next_command"]]
            if command != next_command:
                next_command = f' then {next_command}'
            else:
                next_command = ''
            if current_measurement["command"] == 4:
                command_str = f'Command: {command}{next_command}.'
            else:
                command_str = f'Command: {command} in {dist_to_command} meter{next_command}.'
            target_options.append(command_str)
            
            if getattr(self, "use_lmdrive_commands", False):
                lmdrive_index = random.choice(command_template_mappings[current_measurement["command"]])
                lmdrive_command = random.choice(self.command_templates[str(lmdrive_index)])
                lmdrive_command = lmdrive_command.replace('[x]', str(dist_to_command))
                lm_command = f'Command: {lmdrive_command}.'
                target_options.append(lm_command)
        
        return target_options, placeholder_values

    def equal_spacing_route(self, points):
        route = np.concatenate((np.zeros_like(points[:1]),  points)) # Add 0 to front
        shift = np.roll(route, 1, axis=0) # Shift by 1
        shift[0] = shift[1] # Set wraparound value to 0

        dists = np.linalg.norm(route-shift, axis=1)
        dists = np.cumsum(dists)
        dists += np.arange(0, len(dists))*1e-4 # Prevents dists not being strictly increasing

        x = np.arange(0, 20, 1)
        interp_points = np.array([np.interp(x, dists, route[:, 0]), np.interp(x, dists, route[:, 1])]).T

        return interp_points
    
    def visualise_cameras(
        self,
        batch: Any,
        language, route, waypoints,
        options,
        name: str = "img",
        prompt=None,
        answer=None,
    ) -> np.ndarray:
        
        fov = 110

        img_front_np = batch.image_ff_org_size #[0, ...]
        img_front_np = img_front_np.transpose(0, 2, 3, 1)
        # two patches..dim 1 of img_front is 2 (left and right patches)
        # concatenate them to get a single image
        # img_front_1 = img_front[:, 0, ...]
        # img_front_2 = img_front[:, 1, ...]
        # img_front_torch = torch.cat((img_front_1, img_front_2), dim=3)

        all_images = [Image.fromarray((img_front_np[i])) for i in range(1)]

        # all_images = [Image.fromarray((img_front_torch[i].cpu().permute(1, 2, 0).numpy())) for i in range(1)]
        all_draws = [ImageDraw.Draw(image) for image in all_images]
        
        # black image to be concatenated to the bottom of the image
        img_width = all_images[0].size[0]
        text_box = [Image.new("RGB", (img_width, 200), "black") for _ in range(1)]
        text_draw = [ImageDraw.Draw(image) for image in text_box]
        
        W=all_images[0].size[0]
        H=all_images[0].size[1]
        camera_intrinsics = np.asarray(get_camera_intrinsics(W,H,fov))

        for i in range(1):
            gt_waypoints_img_coords = project_points(batch.waypoints, camera_intrinsics)
            for points_2d in gt_waypoints_img_coords:
                all_draws[i].ellipse((points_2d[0]-3, points_2d[1]-3, points_2d[0]+3, points_2d[1]+3), fill=(0, 255, 0, 255))

            if route is not None:
                pred_route_img_coords = project_points(route, camera_intrinsics)
                for points_2d in pred_route_img_coords:
                    all_draws[i].ellipse((points_2d[0]-2, points_2d[1]-2, points_2d[0]+2, points_2d[1]+2), fill=(255, 0, 0, 255))

            if language is not None:
                y_curr = 10
                
                # write the language to the bottom of the image
                # all_draws[i].rectangle([0, H-60, W, H], fill=(0, 0, 0, 255))
                # all_draws[i].text((10, H-40), f"Pred: {language[i]}", fill=(255, 255, 255, 255))
                text_draw[i].text((10, y_curr), f"Commentary: {language}", fill=(255, 255, 255, 255))
            if prompt is not None:
                text_draw[i].text((10, 30), f"Prompt: {prompt}", fill=(255, 255, 255, 255))
            if answer is not None:
                text_draw[i].text((10, 50), f"Answer: {answer}", fill=(255, 255, 255, 255))
                
        # concat text box to the bottom of the image
        
        # duplicate all_images len(all_negatives) times, deepcopy!
        if options is not None:
            all_all_images = [None for _ in range(len(options))]
            all_blacks = [None for _ in range(len(options))]
            for i, option in enumerate(options):
                wp_altern = option['waypoints']
                route_altern = option['route']
                if isinstance(route_altern, str) and route_altern == 'org':
                    route_altern = route
                if 'dreamer_instruction' in option:
                    language = option['dreamer_instruction'][0] if isinstance(option['dreamer_instruction'], list) else option['dreamer_instruction']
                    answer = option['dreamer_answer_safety'][0] if isinstance(option['dreamer_answer_safety'], list) else option['dreamer_answer_safety']
                else:
                    language = None
                    answer = None
                img = all_images[0].copy()
                draw = ImageDraw.Draw(img)
                img_black = text_box[0].copy()
                draw_black = ImageDraw.Draw(img_black)
                gt_waypoints_img_coords = project_points(wp_altern, camera_intrinsics)
                for points_2d in gt_waypoints_img_coords:
                    draw.ellipse((points_2d[0]-3, points_2d[1]-3, points_2d[0]+3, points_2d[1]+3), fill=(0, 55, 0, 255))
                if route_altern is not None:
                    pred_route_img_coords = project_points(route_altern, camera_intrinsics)
                    for points_2d in pred_route_img_coords:
                        draw.ellipse((points_2d[0]-2, points_2d[1]-2, points_2d[0]+2, points_2d[1]+2), fill=(55, 0, 0, 255))
                if language is not None:
                    draw_black.text((10, 80), f"Alternative Traj: {language}", fill=(255, 255, 255, 255))
                    draw_black.text((10, 100), f"Alternative Traj: {answer}", fill=(255, 255, 255, 255))
                    
                all_all_images[i] = img
                all_blacks[i] = img_black
            
        all_images = [Image.fromarray(np.concatenate([np.array(image), np.array(text)], axis=0)) for image, text in zip(all_images, text_box)]
        if options is not None:
            all_images.extend([Image.fromarray(np.concatenate([np.array(image), np.array(text)], axis=0)) for image, text in zip(all_all_images, all_blacks)])
        
        # concat all images
        viz_image_np = np.concatenate([np.array(image) for image in all_images], axis=0)
        viz_image = Image.fromarray(viz_image_np)
        
        # get ucrrent work dir
        current_dir = os.getcwd()
        
        Path("viz_images").mkdir(parents=True, exist_ok=True)
        # save the image
        time = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
        viz_image.save(f"viz_images/{name}_{time}.png")

        return viz_image_np
    

    def get_indices_speed_angle(self, target_speed, brake):
        target_speeds = [0.0, 4.0, 8.0, 10, 13.88888888, 16, 17.77777777, 20, 24]  # v4 target speeds (0.72*speed limits) plus extra classes for obstacle scenarios and intersecions

        target_speed_bins = [x+0.001 for x in target_speeds[1:]]  
        target_speed_index = np.digitize(x=target_speed, bins=target_speed_bins)

        # Define the first index to be the brake action
        if brake:
            target_speed_index = 0
        else:
            target_speed_index += 1

        return target_speed_index

    def augment_route(self, route, y_augmentation=0.0, yaw_augmentation=0.0):
        aug_yaw_rad = np.deg2rad(yaw_augmentation)
        rotation_matrix = np.array([[np.cos(aug_yaw_rad), -np.sin(aug_yaw_rad)], [np.sin(aug_yaw_rad),
                                                                                    np.cos(aug_yaw_rad)]])

        translation = np.array([[0.0, y_augmentation]])
        route_aug = (rotation_matrix.T @ (route - translation).T).T
        return route_aug

    def augment_target_point(self, target_point, y_augmentation=0.0, yaw_augmentation=0.0):
        aug_yaw_rad = np.deg2rad(yaw_augmentation)
        rotation_matrix = np.array([[np.cos(aug_yaw_rad), -np.sin(aug_yaw_rad)], [np.sin(aug_yaw_rad),
                                                                                np.cos(aug_yaw_rad)]])

        translation = np.array([[0.0], [y_augmentation]])
        pos = np.expand_dims(target_point, axis=1)
        target_point_aug = rotation_matrix.T @ (pos - translation)
        return np.squeeze(target_point_aug)

    def parse_bounding_boxes(self, boxes, future_boxes=None, y_augmentation=0.0, yaw_augmentation=0):

        bboxes = []
        for current_box in boxes:
            # Ego car is always at the origin. We don't predict it.
            if current_box['class'] == 'ego_car':
                continue

            if 'position' not in current_box or 'extent' not in current_box:
                continue

            bbox, height = self.get_bbox_label(current_box, y_augmentation, yaw_augmentation)

            if current_box['class'] == 'traffic_light':
                # Only use/detect boxes that are red and affect the ego vehicle
                if not current_box['affects_ego']:
                    continue

            if current_box['class'] == 'stop_sign':
                # Don't detect cleared stop signs.
                if not current_box['affects_ego']:
                    continue

            bboxes.append(bbox)
        return bboxes

    def get_bbox_label(self, bbox_dict, y_augmentation=0.0, yaw_augmentation=0):
        # augmentation
        aug_yaw_rad = np.deg2rad(yaw_augmentation)
        rotation_matrix = np.array([[np.cos(aug_yaw_rad), -np.sin(aug_yaw_rad)], [np.sin(aug_yaw_rad),
                                                                                np.cos(aug_yaw_rad)]])

        position = np.array([[bbox_dict['position'][0]], [bbox_dict['position'][1]]])
        translation = np.array([[0.0], [y_augmentation]])

        position_aug = rotation_matrix.T @ (position - translation)

        x, y = position_aug[:2, 0]
        # center_x, center_y, w, h, yaw
        bbox = np.array([x, y, bbox_dict['extent'][0], bbox_dict['extent'][1], 0, 0, 0, 0, 0])
        bbox[4] = normalize_angle(bbox_dict['yaw'] - aug_yaw_rad)

        if bbox_dict['class'] == 'car':
            bbox[5] = bbox_dict['speed']
            bbox[6] = bbox_dict['brake']
            bbox[7] = 0
        elif bbox_dict['class'] == 'walker':
            bbox[5] = bbox_dict['speed']
            bbox[7] = 1
        elif bbox_dict['class'] == 'traffic_light':
            bbox[7] = 2
            if bbox_dict['state'] == 'Green':
                bbox[8] = 0
            elif bbox_dict['state'] == 'Red' or bbox_dict['state'] == 'Yellow':
                bbox[8] = 1
            else:
                bbox[8] = 2
        elif bbox_dict['class'] == 'stop_sign':
            bbox[7] = 3

        else:
            bbox = np.zeros(9)
        return bbox, bbox_dict['position'][2]

    def get_route_image(self, route, target_point):
        route_img = np.zeros((64, 64, 3), dtype=np.uint8)
        route_new = np.array(route, dtype=np.float32)
        route_new[:, 0] = -route_new[:, 0]*2 + 63
        route_new[:, 1] = route_new[:, 1]*2 + 32
        route_new = route_new.clip(0, 63)
        route_new = route_new.astype(np.int32)
        route_img[route_new[:, 0], route_new[:, 1], :] = 255

        # # target point as red
        # target_point = np.array(target_point, dtype=np.float32)
        # target_point[0] = -target_point[0]*2 + 63
        # target_point[1] = target_point[1]*2 + 32
        # target_point = target_point.astype(np.int32)
        # # target_point = target_point.clip(0, 63)
        # route_img[target_point[0], target_point[1], 0] = 255

        # save route_img
        # cv2.imwrite('/home/wayve/katrinrenz/coding/WayveCode/route_img.png', route_img)

        return route_img

    def get_waypoints(self, measurements, y_augmentation=0.0, yaw_augmentation=0.0):
        """transform waypoints to be origin at ego_matrix"""
        origin = measurements[0]
        origin_matrix = np.array(origin['ego_matrix'])[:3]
        origin_translation = origin_matrix[:, 3:4]
        origin_rotation = origin_matrix[:, :3]

        waypoints = []
        for index in range(len(measurements)):
            waypoint = np.array(measurements[index]['ego_matrix'])[:3, 3:4]
            waypoint_ego_frame = origin_rotation.T @ (waypoint - origin_translation)
            # Drop the height dimension because we predict waypoints in BEV
            waypoints.append(waypoint_ego_frame[:2, 0])

        # Data augmentation
        waypoints_aug = []
        aug_yaw_rad = np.deg2rad(yaw_augmentation)
        rotation_matrix = np.array([[np.cos(aug_yaw_rad), -np.sin(aug_yaw_rad)], [np.sin(aug_yaw_rad),
                                                                                                                                                            np.cos(aug_yaw_rad)]])

        translation = np.array([[0.0], [y_augmentation]])
        for waypoint in waypoints:
            pos = np.expand_dims(waypoint, axis=1)
            waypoint_aug = rotation_matrix.T @ (pos - translation)
            waypoints_aug.append(np.squeeze(waypoint_aug))

        return waypoints_aug

def image_augmenter(prob=0.2, cutout=False):
    augmentations = [
        ia.Sometimes(prob, ia.GaussianBlur((0, 1.0))),
        ia.Sometimes(prob, ia.AdditiveGaussianNoise(loc=0, scale=(0., 0.05 * 255), per_channel=0.5)),
        ia.Sometimes(prob, ia.Dropout((0.01, 0.1), per_channel=0.5)),  # Strong
        ia.Sometimes(prob, ia.Multiply((1 / 1.2, 1.2), per_channel=0.5)),
        ia.Sometimes(prob, ia.LinearContrast((1 / 1.2, 1.2), per_channel=0.5)),
        ia.Sometimes(prob, ia.Grayscale((0.0, 0.5))),
        ia.Sometimes(prob, ia.ElasticTransformation(alpha=(0.5, 1.5), sigma=0.25)),
    ]

    if cutout:
        augmentations.append(ia.Sometimes(prob, ia.arithmetic.Cutout(squared=False)))

    augmenter = ia.Sequential(augmentations, random_order=True)

    return augmenter


def get_camera_intrinsics(w, h, fov):
    """
    Get camera intrinsics matrix from width, height and fov.
    Returns:
        K: A float32 tensor of shape ``[3, 3]`` containing the intrinsic calibration matrices for
            the carla camera.
    """

    # print(f"[CAMERA MATRIX] Load camera intrinsics for TF++ default camera with w: {w}, h: {h}, fov: {fov}")

    focal = w / (2.0 * np.tan(fov * np.pi / 360.0))
    K = np.identity(3)
    K[0, 0] = K[1, 1] = focal
    K[0, 2] = w / 2.0
    K[1, 2] = h / 2.0

    K = torch.tensor(K, dtype=torch.float32)
    return K

def get_camera_extrinsics():
    """
    Get camera extrinsics matrix for the carla camera.
    extrinsics: A float32 tensor of shape ``[4, 4]`` containing the extrinic calibration matrix for
            the carla camera. The extriniscs are specified as homogeneous matrices of the form ``[R t; 0 1]``
    """

    # camera_pos = [-1.5, 0.0, 2.0]  # x, y, z mounting position of the camera
    # camera_rot_0 = [0.0, 0.0, 0.0]  # Roll Pitch Yaw of camera 0 in degree

    # print("[CAMERA MATRIX] Load camera extrinsics for TF++ default camera with x: -1.5, y: 0.0, z: 2.0, roll: 0.0, pitch: 0.0, yaw: 0.0")
    extrinsics = np.zeros((4, 4), dtype=np.float32)
    extrinsics[3, 3] = 1.0
    extrinsics[:3, :3] = np.eye(3)
    extrinsics[:3, 3] = [-1.5, 0.0, 2.0]

    extrinsics = torch.tensor(extrinsics, dtype=torch.float32)

    return extrinsics

def get_camera_distortion():
    """
    Get camera distortion matrix for the carla camera.
    distortion: A float32 tensor of shape ``[14 + 1]`` containing the camera distortion co-efficients
            ``[k0, k1, ..., k13, d]`` where ``k0`` to ``k13`` are distortion co-efficients and d specifies the
            distortion model as defined by the DistortionType enum in camera_info.hpp
    """

    print("[CAMERA MATRIX] Load camera distortion for TF++ default camera. No distortion.")
    distortion = np.zeros(14 + 1, dtype=np.float32)
    distortion[-1] = 0.0
    distortion = torch.tensor(distortion, dtype=torch.float32)

    return distortion




if __name__ == "__main__":
    from hydra import compose, initialize
    from config import TrainConfig
    
    # set all seeds
    torch.manual_seed(0)
    np.random.seed(0)
    random.seed(0)
    
    

    initialize(config_path="../config")
    cfg = compose(config_name="config")
    
    cfg.data_module.base_dataset.use_commentary = False
    cfg.data_module.base_dataset.img_shift_augmentation = True
    
    cfg.data_module.base_dataset.use_safety_flag = True

    print('Test Dataset')
    dataset = Data_Dreamer(                        
                        split="train",
                        bucket_name='all',
                        **cfg.data_module,
                        **cfg.data_module.base_dataset,
    )

    for i in range(len(dataset)):
        data = dataset[i]
        print(data)
        if i == 100:
            break