File size: 117,448 Bytes
663494c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
# nuScenes dev-kit.
# Code written by Sergi Adipraja Widjaja, 2019.
# + Map mask by Kiwoo Shin, 2019.
# + Methods operating on NuScenesMap and NuScenes by Holger Caesar, 2019.

import json
import os
import random
from typing import Dict, List, Tuple, Optional, Union

import cv2
import math
import descartes
import matplotlib.gridspec as gridspec
import matplotlib.pyplot as plt
import numpy as np
from PIL import Image
from matplotlib.axes import Axes
from matplotlib.figure import Figure
from matplotlib.patches import Rectangle, Arrow
from mpl_toolkits.axes_grid1.inset_locator import mark_inset
from pyquaternion import Quaternion
from shapely import affinity
from shapely.geometry import Polygon, MultiPolygon, LineString, Point, box
from tqdm import tqdm

from nuscenes.map_expansion.arcline_path_utils import discretize_lane, ArcLinePath
from nuscenes.map_expansion.bitmap import BitMap
from nuscenes.nuscenes import NuScenes
from nuscenes.utils.geometry_utils import view_points
from functools import partial

# Recommended style to use as the plots will show grids.
plt.style.use("seaborn-whitegrid")

# Define a map geometry type for polygons and lines.
Geometry = Union[Polygon, LineString]

locations = [
    "singapore-onenorth",
    "singapore-hollandvillage",
    "singapore-queenstown",
    "boston-seaport",
]


class NuScenesMap:
    """
    NuScenesMap database class for querying and retrieving information from the semantic maps.
    Before using this class please use the provided tutorial `map_expansion_tutorial.ipynb`.

    Below you can find the map origins (south western corner, in [lat, lon]) for each of the 4 maps in nuScenes:
    boston-seaport: [42.336849169438615, -71.05785369873047]
    singapore-onenorth: [1.2882100868743724, 103.78475189208984]
    singapore-hollandvillage: [1.2993652317780957, 103.78217697143555]
    singapore-queenstown: [1.2782562240223188, 103.76741409301758]

    The dimensions of the maps are as follows ([width, height] in meters):
    singapore-onenorth: [1585.6, 2025.0]
    singapore-hollandvillage: [2808.3, 2922.9]
    singapore-queenstown: [3228.6, 3687.1]
    boston-seaport: [2979.5, 2118.1]
    The rasterized semantic maps (e.g. singapore-onenorth.png) published with nuScenes v1.0 have a scale of 10px/m,
    hence the above numbers are the image dimensions divided by 10.

    We use the same WGS 84 Web Mercator (EPSG:3857) projection as Google Maps/Earth.
    """

    def __init__(
        self,
        dataroot: str = "/data/sets/nuscenes",
        map_name: str = "singapore-onenorth",
    ):
        """
        Loads the layers, create reverse indices and shortcuts, initializes the explorer class.
        :param dataroot: Path to the layers in the form of a .json file.
        :param map_name: Which map out of `singapore-onenorth`, `singepore-hollandvillage`, `singapore-queenstown`,
        `boston-seaport` that we want to load.
        """
        assert map_name in locations, "Error: Unknown map name %s!" % map_name

        self.dataroot = dataroot
        self.map_name = map_name

        self.geometric_layers = ["polygon", "line", "node"]

        # These are the non-geometric layers which have polygons as the geometric descriptors.
        self.non_geometric_polygon_layers = [
            "drivable_area",
            "road_segment",
            "road_block",
            "lane",
            "ped_crossing",
            "walkway",
            "stop_line",
            "carpark_area",
        ]

        # We want to be able to search for lane connectors, but not render them.
        self.lookup_polygon_layers = self.non_geometric_polygon_layers + [
            "lane_connector"
        ]

        # These are the non-geometric layers which have line strings as the geometric descriptors.
        self.non_geometric_line_layers = [
            "road_divider",
            "lane_divider",
            "traffic_light",
        ]
        self.non_geometric_layers = (
            self.non_geometric_polygon_layers + self.non_geometric_line_layers
        )
        self.layer_names = (
            self.geometric_layers
            + self.lookup_polygon_layers
            + self.non_geometric_line_layers
        )

        # Load the selected map.
        self.json_fname = os.path.join(
            self.dataroot, "maps", "expansion", "{}.json".format(self.map_name)
        )
        with open(self.json_fname, "r") as fh:
            self.json_obj = json.load(fh)

        # Parse the map version and print an error for deprecated maps.
        if "version" in self.json_obj:
            self.version = self.json_obj["version"]
        else:
            self.version = "1.0"
        if self.version < "1.3":
            raise Exception(
                "Error: You are using an outdated map version (%s)! "
                "Please go to https://www.nuscenes.org/download to download the latest map!"
            )

        self.canvas_edge = self.json_obj["canvas_edge"]
        self._load_layers()
        self._make_token2ind()
        self._make_shortcuts()

        self.explorer = NuScenesMapExplorer(self)

    def _load_layer(self, layer_name: str) -> List[dict]:
        """
        Returns a list of records corresponding to the layer name.
        :param layer_name: Name of the layer that will be loaded.
        :return: A list of records corresponding to a layer.
        """
        return self.json_obj[layer_name]

    def _load_layer_dict(self, layer_name: str) -> Dict[str, Union[dict, list]]:
        """
        Returns a dict of records corresponding to the layer name.
        :param layer_name: Name of the layer that will be loaded.
        :return: A dict of records corresponding to a layer.
        """
        return self.json_obj[layer_name]

    def _load_layers(self) -> None:
        """ Loads each available layer. """

        # Explicit assignment of layers are necessary to help the IDE determine valid class members.
        self.polygon = self._load_layer("polygon")
        self.line = self._load_layer("line")
        self.node = self._load_layer("node")
        self.drivable_area = self._load_layer("drivable_area")
        self.road_segment = self._load_layer("road_segment")
        self.road_block = self._load_layer("road_block")
        self.lane = self._load_layer("lane")
        self.ped_crossing = self._load_layer("ped_crossing")
        self.walkway = self._load_layer("walkway")
        self.stop_line = self._load_layer("stop_line")
        self.carpark_area = self._load_layer("carpark_area")
        self.road_divider = self._load_layer("road_divider")
        self.lane_divider = self._load_layer("lane_divider")
        self.traffic_light = self._load_layer("traffic_light")

        self.arcline_path_3: Dict[str, List[dict]] = self._load_layer_dict(
            "arcline_path_3"
        )
        self.connectivity: Dict[str, dict] = self._load_layer_dict("connectivity")
        self.lane_connector = self._load_layer("lane_connector")

    def _make_token2ind(self) -> None:
        """ Store the mapping from token to layer index for each layer. """
        self._token2ind = dict()
        for layer_name in self.layer_names:
            self._token2ind[layer_name] = dict()

            for ind, member in enumerate(getattr(self, layer_name)):
                self._token2ind[layer_name][member["token"]] = ind

    def _make_shortcuts(self) -> None:
        """ Makes the record shortcuts. """

        # Makes a shortcut between non geometric records to their nodes.
        for layer_name in self.non_geometric_polygon_layers:
            if (
                layer_name == "drivable_area"
            ):  # Drivable area has more than one geometric representation.
                pass
            else:
                for record in self.__dict__[layer_name]:
                    polygon_obj = self.get("polygon", record["polygon_token"])
                    record["exterior_node_tokens"] = polygon_obj["exterior_node_tokens"]
                    record["holes"] = polygon_obj["holes"]

        for layer_name in self.non_geometric_line_layers:
            for record in self.__dict__[layer_name]:
                record["node_tokens"] = self.get("line", record["line_token"])[
                    "node_tokens"
                ]

        # Makes a shortcut between stop lines to their cues, there's different cues for different types of stop line.
        # Refer to `_get_stop_line_cue()` for details.
        for record in self.stop_line:
            cue = self._get_stop_line_cue(record)
            record["cue"] = cue

        # Makes a shortcut between lanes to their lane divider segment nodes.
        for record in self.lane:
            record["left_lane_divider_segment_nodes"] = [
                self.get("node", segment["node_token"])
                for segment in record["left_lane_divider_segments"]
            ]
            record["right_lane_divider_segment_nodes"] = [
                self.get("node", segment["node_token"])
                for segment in record["right_lane_divider_segments"]
            ]

    def _get_stop_line_cue(self, stop_line_record: dict) -> List[dict]:
        """
        Get the different cues for different types of stop lines.
        :param stop_line_record: A single stop line record.
        :return: The cue for that stop line.
        """
        if stop_line_record["stop_line_type"] in ["PED_CROSSING", "TURN_STOP"]:
            return [
                self.get("ped_crossing", token)
                for token in stop_line_record["ped_crossing_tokens"]
            ]
        elif stop_line_record["stop_line_type"] in ["STOP_SIGN", "YIELD"]:
            return []
        elif stop_line_record["stop_line_type"] == "TRAFFIC_LIGHT":
            return [
                self.get("traffic_light", token)
                for token in stop_line_record["traffic_light_tokens"]
            ]

    def get(self, layer_name: str, token: str) -> dict:
        """
        Returns a record from the layer in constant runtime.
        :param layer_name: Name of the layer that we are interested in.
        :param token: Token of the record.
        :return: A single layer record.
        """
        assert layer_name in self.layer_names, "Layer {} not found".format(layer_name)

        return getattr(self, layer_name)[self.getind(layer_name, token)]

    def getind(self, layer_name: str, token: str) -> int:
        """
        This returns the index of the record in a layer in constant runtime.
        :param layer_name: Name of the layer we are interested in.
        :param token: Token of the record.
        :return: The index of the record in the layer, layer is an array.
        """
        return self._token2ind[layer_name][token]

    def render_record(
        self,
        layer_name: str,
        token: str,
        alpha: float = 0.5,
        figsize: Tuple[float, float] = None,
        other_layers: List[str] = None,
        bitmap: Optional[BitMap] = None,
    ) -> Tuple[Figure, Tuple[Axes, Axes]]:
        """
        Render a single map record. By default will also render 3 layers which are `drivable_area`, `lane`,
        and `walkway` unless specified by `other_layers`.
        :param layer_name: Name of the layer that we are interested in.
        :param token: Token of the record that you want to render.
        :param alpha: The opacity of each layer that gets rendered.
        :param figsize: Size of the whole figure.
        :param other_layers: What other layers to render aside from the one specified in `layer_name`.
        :param bitmap: Optional BitMap object to render below the other map layers.
        :return: The matplotlib figure and axes of the rendered layers.
        """
        return self.explorer.render_record(
            layer_name,
            token,
            alpha,
            figsize=figsize,
            other_layers=other_layers,
            bitmap=bitmap,
        )

    def render_layers(
        self,
        layer_names: List[str],
        alpha: float = 0.5,
        figsize: Union[None, float, Tuple[float, float]] = None,
        tokens: List[str] = None,
        bitmap: Optional[BitMap] = None,
    ) -> Tuple[Figure, Axes]:
        """
        Render a list of layer names.
        :param layer_names: A list of layer names.
        :param alpha: The opacity of each layer that gets rendered.
        :param figsize: Size of the whole figure.
        :param tokens: Optional list of tokens to render. None means all tokens are rendered.
        :param bitmap: Optional BitMap object to render below the other map layers.
        :return: The matplotlib figure and axes of the rendered layers.
        """
        return self.explorer.render_layers(
            layer_names, alpha, figsize=figsize, tokens=tokens, bitmap=bitmap
        )

    def render_map_patch(
        self,
        box_coords: Tuple[float, float, float, float],
        layer_names: List[str] = None,
        alpha: float = 0.5,
        figsize: Tuple[int, int] = (15, 15),
        render_egoposes_range: bool = True,
        render_legend: bool = True,
        bitmap: Optional[BitMap] = None,
    ) -> Tuple[Figure, Axes]:
        """
        Renders a rectangular patch specified by `box_coords`. By default renders all layers.
        :param box_coords: The rectangular patch coordinates (x_min, y_min, x_max, y_max).
        :param layer_names: All the non geometric layers that we want to render.
        :param alpha: The opacity of each layer.
        :param figsize: Size of the whole figure.
        :param render_egoposes_range: Whether to render a rectangle around all ego poses.
        :param render_legend: Whether to render the legend of map layers.
        :param bitmap: Optional BitMap object to render below the other map layers.
        :return: The matplotlib figure and axes of the rendered layers.
        """
        return self.explorer.render_map_patch(
            box_coords,
            layer_names=layer_names,
            alpha=alpha,
            figsize=figsize,
            render_egoposes_range=render_egoposes_range,
            render_legend=render_legend,
            bitmap=bitmap,
        )

    def render_map_in_image(
        self,
        nusc: NuScenes,
        sample_token: str,
        camera_channel: str = "CAM_FRONT",
        alpha: float = 0.3,
        patch_radius: float = 10000,
        min_polygon_area: float = 1000,
        render_behind_cam: bool = True,
        render_outside_im: bool = True,
        layer_names: List[str] = None,
        verbose: bool = True,
        out_path: str = None,
    ) -> Tuple[Figure, Axes]:
        """
        Render a nuScenes camera image and overlay the polygons for the specified map layers.
        Note that the projections are not always accurate as the localization is in 2d.
        :param nusc: The NuScenes instance to load the image from.
        :param sample_token: The image's corresponding sample_token.
        :param camera_channel: Camera channel name, e.g. 'CAM_FRONT'.
        :param alpha: The transparency value of the layers to render in [0, 1].
        :param patch_radius: The radius in meters around the ego car in which to select map records.
        :param min_polygon_area: Minimum area a polygon needs to have to be rendered.
        :param render_behind_cam: Whether to render polygons where any point is behind the camera.
        :param render_outside_im: Whether to render polygons where any point is outside the image.
        :param layer_names: The names of the layers to render, e.g. ['lane'].
            If set to None, the recommended setting will be used.
        :param verbose: Whether to print to stdout.
        :param out_path: Optional path to save the rendered figure to disk.
        """
        return self.explorer.render_map_in_image(
            nusc,
            sample_token,
            camera_channel=camera_channel,
            alpha=alpha,
            patch_radius=patch_radius,
            min_polygon_area=min_polygon_area,
            render_behind_cam=render_behind_cam,
            render_outside_im=render_outside_im,
            layer_names=layer_names,
            verbose=verbose,
            out_path=out_path,
        )

    def get_map_mask_in_image(
        self,
        nusc: NuScenes,
        sample_token: str,
        camera_channel: str = "CAM_FRONT",
        alpha: float = 0.3,
        patch_radius: float = 10000,
        min_polygon_area: float = 1000,
        render_behind_cam: bool = True,
        render_outside_im: bool = True,
        layer_names: List[str] = None,
        verbose: bool = False,
        out_path: str = None,
    ):
        """
        Render a nuScenes camera image and overlay the polygons for the specified map layers.
        Note that the projections are not always accurate as the localization is in 2d.
        :param nusc: The NuScenes instance to load the image from.
        :param sample_token: The image's corresponding sample_token.
        :param camera_channel: Camera channel name, e.g. 'CAM_FRONT'.
        :param alpha: The transparency value of the layers to render in [0, 1].
        :param patch_radius: The radius in meters around the ego car in which to select map records.
        :param min_polygon_area: Minimum area a polygon needs to have to be rendered.
        :param render_behind_cam: Whether to render polygons where any point is behind the camera.
        :param render_outside_im: Whether to render polygons where any point is outside the image.
        :param layer_names: The names of the layers to render, e.g. ['lane'].
            If set to None, the recommended setting will be used.
        :param verbose: Whether to print to stdout.
        :param out_path: Optional path to save the rendered figure to disk.
        """
        return self.explorer.get_map_mask_in_image(
            nusc,
            sample_token,
            camera_channel=camera_channel,
            alpha=alpha,
            patch_radius=patch_radius,
            min_polygon_area=min_polygon_area,
            render_behind_cam=render_behind_cam,
            render_outside_im=render_outside_im,
            layer_names=layer_names,
            verbose=verbose,
            out_path=out_path,
        )

    def render_egoposes_on_fancy_map(
        self,
        nusc: NuScenes,
        scene_tokens: List = None,
        verbose: bool = True,
        out_path: str = None,
        render_egoposes: bool = True,
        render_egoposes_range: bool = True,
        render_legend: bool = True,
        bitmap: Optional[BitMap] = None,
    ) -> Tuple[np.ndarray, Figure, Axes]:
        """
        Renders each ego pose of a list of scenes on the map (around 40 poses per scene).
        This method is heavily inspired by NuScenes.render_egoposes_on_map(), but uses the map expansion pack maps.
        :param nusc: The NuScenes instance to load the ego poses from.
        :param scene_tokens: Optional list of scene tokens corresponding to the current map location.
        :param verbose: Whether to show status messages and progress bar.
        :param out_path: Optional path to save the rendered figure to disk.
        :param render_egoposes: Whether to render ego poses.
        :param render_egoposes_range: Whether to render a rectangle around all ego poses.
        :param render_legend: Whether to render the legend of map layers.
        :param bitmap: Optional BitMap object to render below the other map layers.
        :return: <np.float32: n, 2>. Returns a matrix with n ego poses in global map coordinates.
        """
        return self.explorer.render_egoposes_on_fancy_map(
            nusc,
            scene_tokens=scene_tokens,
            verbose=verbose,
            out_path=out_path,
            render_egoposes=render_egoposes,
            render_egoposes_range=render_egoposes_range,
            render_legend=render_legend,
            bitmap=bitmap,
        )

    def render_centerlines(
        self,
        resolution_meters: float = 0.5,
        figsize: Union[None, float, Tuple[float, float]] = None,
        bitmap: Optional[BitMap] = None,
    ) -> Tuple[Figure, Axes]:
        """
        Render the centerlines of all lanes and lane connectors.
        :param resolution_meters: How finely to discretize the lane. Smaller values ensure curved
            lanes are properly represented.
        :param figsize: Size of the figure.
        :param bitmap: Optional BitMap object to render below the other map layers.
        """
        return self.explorer.render_centerlines(
            resolution_meters=resolution_meters, figsize=figsize, bitmap=bitmap
        )

    def render_map_mask(
        self,
        patch_box: Tuple[float, float, float, float],
        patch_angle: float,
        layer_names: List[str] = None,
        canvas_size: Tuple[int, int] = (100, 100),
        figsize: Tuple[int, int] = (15, 15),
        n_row: int = 2,
    ) -> Tuple[Figure, List[Axes]]:
        """
        Render map mask of the patch specified by patch_box and patch_angle.
        :param patch_box: Patch box defined as [x_center, y_center, height, width].
        :param patch_angle: Patch orientation in degrees.
        :param layer_names: A list of layer names to be returned.
        :param canvas_size: Size of the output mask (h, w).
        :param figsize: Size of the figure.
        :param n_row: Number of rows with plots.
        :return: The matplotlib figure and a list of axes of the rendered layers.
        """
        return self.explorer.render_map_mask(
            patch_box,
            patch_angle,
            layer_names=layer_names,
            canvas_size=canvas_size,
            figsize=figsize,
            n_row=n_row,
        )

    def get_map_mask(
        self,
        patch_box: Optional[Tuple[float, float, float, float]],
        patch_angle: float,
        layer_names: List[str] = None,
        canvas_size: Optional[Tuple[int, int]] = (100, 100),
    ) -> np.ndarray:
        """
        Return list of map mask layers of the specified patch.
        :param patch_box: Patch box defined as [x_center, y_center, height, width]. If None, this plots the entire map.
        :param patch_angle: Patch orientation in degrees. North-facing corresponds to 0.
        :param layer_names: A list of layer names to be extracted, or None for all non-geometric layers.
        :param canvas_size: Size of the output mask (h, w). If None, we use the default resolution of 10px/m.
        :return: Stacked numpy array of size [c x h x w] with c channels and the same width/height as the canvas.
        """
        return self.explorer.get_map_mask(
            patch_box, patch_angle, layer_names=layer_names, canvas_size=canvas_size
        )

    def get_map_geom(
        self,
        patch_box: Tuple[float, float, float, float],
        patch_angle: float,
        layer_names: List[str],
    ) -> List[Tuple[str, List[Geometry]]]:
        """
        Returns a list of geometries in the specified patch_box.
        These are unscaled, but aligned with the patch angle.
        :param patch_box: Patch box defined as [x_center, y_center, height, width].
        :param patch_angle: Patch orientation in degrees.
                            North-facing corresponds to 0.
        :param layer_names: A list of layer names to be extracted, or None for all non-geometric layers.
        :return: List of layer names and their corresponding geometries.
        """
        return self.explorer.get_map_geom(patch_box, patch_angle, layer_names)

    def get_records_in_patch(
        self,
        box_coords: Tuple[float, float, float, float],
        layer_names: List[str] = None,
        mode: str = "intersect",
    ) -> Dict[str, List[str]]:
        """
        Get all the record token that intersects or is within a particular rectangular patch.
        :param box_coords: The rectangular patch coordinates (x_min, y_min, x_max, y_max).
        :param layer_names: Names of the layers that we want to retrieve in a particular patch. By default will always
        look at the all non geometric layers.
        :param mode: "intersect" will return all non geometric records that intersects the patch, "within" will return
        all non geometric records that are within the patch.
        :return: Dictionary of layer_name - tokens pairs.
        """
        return self.explorer.get_records_in_patch(
            box_coords, layer_names=layer_names, mode=mode
        )

    def is_record_in_patch(
        self,
        layer_name: str,
        token: str,
        box_coords: Tuple[float, float, float, float],
        mode: str = "intersect",
    ) -> bool:
        """
        Query whether a particular record is in a rectangular patch
        :param layer_name: The layer name of the record.
        :param token: The record token.
        :param box_coords: The rectangular patch coordinates (x_min, y_min, x_max, y_max).
        :param mode: "intersect" means it will return True if the geometric object intersects the patch, "within" will
                     return True if the geometric object is within the patch.
        :return: Boolean value on whether a particular record intersects or within a particular patch.
        """
        return self.explorer.is_record_in_patch(
            layer_name, token, box_coords, mode=mode
        )

    def layers_on_point(
        self, x: float, y: float, layer_names: List[str] = None
    ) -> Dict[str, str]:
        """
        Returns all the polygonal layers that a particular point is on.
        :param x: x coordinate of the point of interest.
        :param y: y coordinate of the point of interest.
        :param layer_names: The names of the layers to search for.
        :return: All the polygonal layers that a particular point is on. {<layer name>: <list of tokens>}
        """
        return self.explorer.layers_on_point(x, y, layer_names=layer_names)

    def record_on_point(self, x: float, y: float, layer_name: str) -> str:
        """
        Query what record of a layer a particular point is on.
        :param x: x coordinate of the point of interest.
        :param y: y coordinate of the point of interest.
        :param layer_name: The non geometric polygonal layer name that we are interested in.
        :return: The first token of a layer a particular point is on or '' if no layer is found.
        """
        return self.explorer.record_on_point(x, y, layer_name)

    def extract_polygon(self, polygon_token: str) -> Polygon:
        """
        Construct a shapely Polygon object out of a polygon token.
        :param polygon_token: The token of the polygon record.
        :return: The polygon wrapped in a shapely Polygon object.
        """
        return self.explorer.extract_polygon(polygon_token)

    def extract_line(self, line_token: str) -> LineString:
        """
        Construct a shapely LineString object out of a line token.
        :param line_token: The token of the line record.
        :return: The line wrapped in a LineString object.
        """
        return self.explorer.extract_line(line_token)

    def get_bounds(
        self, layer_name: str, token: str
    ) -> Tuple[float, float, float, float]:
        """
        Get the bounds of the geometric object that corresponds to a non geometric record.
        :param layer_name: Name of the layer that we are interested in.
        :param token: Token of the record.
        :return: min_x, min_y, max_x, max_y of of the line representation.
        """
        return self.explorer.get_bounds(layer_name, token)

    def get_records_in_radius(
        self,
        x: float,
        y: float,
        radius: float,
        layer_names: List[str],
        mode: str = "intersect",
    ) -> Dict[str, List[str]]:
        """
        Get all the record tokens that intersect a square patch of side length 2*radius centered on (x,y).
        :param x: X-coordinate in global frame.
        :param y: y-coordinate in global frame.
        :param radius: All records within radius meters of point (x, y) will be returned.
        :param layer_names: Names of the layers that we want to retrieve. By default will always
        look at the all non geometric layers.
        :param mode: "intersect" will return all non geometric records that intersects the patch, "within" will return
        all non geometric records that are within the patch.
        :return: Dictionary of layer_name - tokens pairs.
        """

        patch = (x - radius, y - radius, x + radius, y + radius)
        return self.explorer.get_records_in_patch(patch, layer_names, mode=mode)

    def discretize_centerlines(self, resolution_meters: float) -> List[np.array]:
        """
        Discretize the centerlines of lanes and lane connectors.
        :param resolution_meters: How finely to discretize the lane. Smaller values ensure curved
            lanes are properly represented.
        :return: A list of np.arrays with x, y and z values for each point.
        """
        pose_lists = []
        for lane in self.lane + self.lane_connector:
            my_lane = self.arcline_path_3.get(lane["token"], [])
            discretized = np.array(discretize_lane(my_lane, resolution_meters))
            pose_lists.append(discretized)

        return pose_lists

    def discretize_lanes(
        self, tokens: List[str], resolution_meters: float
    ) -> Dict[str, List[Tuple[float, float, float]]]:
        """
        Discretizes a list of lane/lane connector tokens.
        :param tokens: List of lane and/or lane connector record tokens. Can be retrieved with
            get_records_in_radius or get_records_in_patch.
        :param resolution_meters: How finely to discretize the splines.
        :return: Mapping from lane/lane connector token to sequence of poses along the lane.
        """

        return {
            ID: discretize_lane(self.arcline_path_3.get(ID, []), resolution_meters)
            for ID in tokens
        }

    def _get_connected_lanes(
        self, lane_token: str, incoming_outgoing: str
    ) -> List[str]:
        """
        Helper for getting the lanes connected to a given lane
        :param lane_token: Token for the lane.
        :param incoming_outgoing: Whether to get incoming or outgoing lanes
        :return: List of lane tokens this lane is connected to.
        """

        if lane_token not in self.connectivity:
            raise ValueError(f"{lane_token} is not a valid lane.")

        return self.connectivity[lane_token][incoming_outgoing]

    def get_outgoing_lane_ids(self, lane_token: str) -> List[str]:
        """
        Get the out-going lanes.
        :param lane_token: Token for the lane.
        :return: List of lane tokens that start at the end of this lane.
        """

        return self._get_connected_lanes(lane_token, "outgoing")

    def get_incoming_lane_ids(self, lane_token: str) -> List[str]:
        """
        Get the incoming lanes.
        :param lane_token: Token for the lane.
        :return: List of lane tokens that end at the start of this lane.
        """

        return self._get_connected_lanes(lane_token, "incoming")

    def get_arcline_path(self, lane_token: str) -> List[ArcLinePath]:
        """
        Get the arcline path representation for a lane.
        Note: This function was previously called `get_lane()`, but renamed to avoid confusion between lanes and
              arcline paths.
        :param lane_token: Token for the lane.
        :return: Arc line path representation of the lane.
        """

        arcline_path = self.arcline_path_3.get(lane_token)
        if not arcline_path:
            raise ValueError(
                f"Error: Lane with token {lane_token} does not have a valid arcline path!"
            )

        return arcline_path

    def get_closest_lane(self, x: float, y: float, radius: float = 5) -> str:
        """
        Get closest lane id within a radius of query point. The distance from a point (x, y) to a lane is
        the minimum l2 distance from (x, y) to a point on the lane.
        :param x: X coordinate in global coordinate frame.
        :param y: Y Coordinate in global coordinate frame.
        :param radius: Radius around point to consider.
        :return: Lane id of closest lane within radius.
        """

        lanes = self.get_records_in_radius(x, y, radius, ["lane", "lane_connector"])
        lanes = lanes["lane"] + lanes["lane_connector"]

        discrete_points = self.discretize_lanes(lanes, 0.5)

        current_min = np.inf

        min_id = ""
        for lane_id, points in discrete_points.items():

            distance = np.linalg.norm(np.array(points)[:, :2] - [x, y], axis=1).min()
            if distance <= current_min:
                current_min = distance
                min_id = lane_id

        return min_id

    def render_next_roads(
        self,
        x: float,
        y: float,
        alpha: float = 0.5,
        figsize: Union[None, float, Tuple[float, float]] = None,
        bitmap: Optional[BitMap] = None,
    ) -> Tuple[Figure, Axes]:
        """
        Renders the possible next roads from a point of interest.
        :param x: x coordinate of the point of interest.
        :param y: y coordinate of the point of interest.
        :param alpha: The opacity of each layer that gets rendered.
        :param figsize: Size of the whole figure.
        :param bitmap: Optional BitMap object to render below the other map layers.
        """
        return self.explorer.render_next_roads(
            x, y, alpha, figsize=figsize, bitmap=bitmap
        )

    def get_next_roads(self, x: float, y: float) -> Dict[str, List[str]]:
        """
        Get the possible next roads from a point of interest.
        Returns road_segment, road_block and lane.
        :param x: x coordinate of the point of interest.
        :param y: y coordinate of the point of interest.
        :return: Dictionary of layer_name - tokens pairs.
        """
        # Filter out irrelevant layers.
        road_layers = ["road_segment", "road_block", "lane"]
        layers = self.explorer.layers_on_point(x, y)
        rel_layers = {layer: layers[layer] for layer in road_layers}

        # Pick most fine-grained road layer (lane, road_block, road_segment) object that contains the point.
        rel_layer = None
        rel_token = None
        for layer in road_layers[::-1]:
            if rel_layers[layer] != "":
                rel_layer = layer
                rel_token = rel_layers[layer]
                break
        assert (
            rel_layer is not None
        ), "Error: No suitable layer in the specified point location!"

        # Get all records that overlap with the bounding box of the selected road.
        box_coords = self.explorer.get_bounds(rel_layer, rel_token)
        intersect = self.explorer.get_records_in_patch(
            box_coords, road_layers, mode="intersect"
        )

        # Go through all objects within the bounding box.
        result = {layer: [] for layer in road_layers}
        if rel_layer == "road_segment":
            # For road segments, we do not have a direction.
            # Return objects that have ANY exterior points in common with the relevant layer.
            rel_exterior_nodes = self.get(rel_layer, rel_token)["exterior_node_tokens"]
            for layer in road_layers:
                for token in intersect[layer]:
                    exterior_nodes = self.get(layer, token)["exterior_node_tokens"]
                    if (
                        any(n in exterior_nodes for n in rel_exterior_nodes)
                        and token != rel_layers[layer]
                    ):
                        result[layer].append(token)
        else:
            # For lanes and road blocks, the next road is indicated by the edge line.
            # Return objects where ALL edge line nodes are included in the exterior nodes.
            to_edge_line = self.get(rel_layer, rel_token)["to_edge_line_token"]
            to_edge_nodes = self.get("line", to_edge_line)["node_tokens"]
            for layer in road_layers:
                for token in intersect[layer]:
                    exterior_nodes = self.get(layer, token)["exterior_node_tokens"]
                    if (
                        all(n in exterior_nodes for n in to_edge_nodes)
                        and token != rel_layers[layer]
                    ):
                        result[layer].append(token)
        return result


class NuScenesMapExplorer:
    """ Helper class to explore the nuScenes map data. """

    def __init__(
        self,
        map_api: NuScenesMap,
        representative_layers: Tuple[str] = ("drivable_area", "lane", "walkway"),
        color_map: dict = None,
    ):
        """
        :param map_api: NuScenesMap database class.
        :param representative_layers: These are the layers that we feel are representative of the whole mapping data.
        :param color_map: Color map.
        """
        # Mutable default argument.
        if color_map is None:
            color_map = dict(
                drivable_area="#a6cee3",
                road_segment="#1f78b4",
                road_block="#b2df8a",
                lane="#33a02c",
                ped_crossing="#fb9a99",
                walkway="#e31a1c",
                stop_line="#fdbf6f",
                carpark_area="#ff7f00",
                road_divider="#cab2d6",
                lane_divider="#6a3d9a",
                traffic_light="#7e772e",
            )

        self.map_api = map_api
        self.representative_layers = representative_layers
        self.color_map = color_map

        self.canvas_max_x = self.map_api.canvas_edge[0]
        self.canvas_min_x = 0
        self.canvas_max_y = self.map_api.canvas_edge[1]
        self.canvas_min_y = 0
        self.canvas_aspect_ratio = (self.canvas_max_x - self.canvas_min_x) / (
            self.canvas_max_y - self.canvas_min_y
        )

    def render_centerlines(
        self,
        resolution_meters: float,
        figsize: Union[None, float, Tuple[float, float]] = None,
        bitmap: Optional[BitMap] = None,
    ) -> Tuple[Figure, Axes]:
        """
        Render the centerlines of all lanes and lane connectors.
        :param resolution_meters: How finely to discretize the lane. Smaller values ensure curved
            lanes are properly represented.
        :param figsize: Size of the figure.
        :param bitmap: Optional BitMap object to render below the other map layers.
        """
        # Discretize all lanes and lane connectors.
        pose_lists = self.map_api.discretize_centerlines(resolution_meters)

        # Render connectivity lines.
        fig = plt.figure(figsize=self._get_figsize(figsize))
        ax = fig.add_axes([0, 0, 1, 1 / self.canvas_aspect_ratio])

        if bitmap is not None:
            bitmap.render(self.map_api.canvas_edge, ax)

        for pose_list in pose_lists:
            if len(pose_list) > 0:
                plt.plot(pose_list[:, 0], pose_list[:, 1])

        return fig, ax

    def render_map_mask(
        self,
        patch_box: Tuple[float, float, float, float],
        patch_angle: float,
        layer_names: List[str],
        canvas_size: Tuple[int, int],
        figsize: Tuple[int, int],
        n_row: int = 2,
    ) -> Tuple[Figure, List[Axes]]:
        """
        Render map mask of the patch specified by patch_box and patch_angle.
        :param patch_box: Patch box defined as [x_center, y_center, height, width].
        :param patch_angle: Patch orientation in degrees.
        :param layer_names: A list of layer names to be extracted.
        :param canvas_size: Size of the output mask (h, w).
        :param figsize: Size of the figure.
        :param n_row: Number of rows with plots.
        :return: The matplotlib figure and a list of axes of the rendered layers.
        """
        if layer_names is None:
            layer_names = self.map_api.non_geometric_layers

        map_mask = self.get_map_mask(patch_box, patch_angle, layer_names, canvas_size)

        # If no canvas_size is specified, retrieve the default from the output of get_map_mask.
        if canvas_size is None:
            canvas_size = map_mask.shape[1:]

        fig = plt.figure(figsize=figsize)
        ax = fig.add_axes([0, 0, 1, 1])
        ax.set_xlim(0, canvas_size[1])
        ax.set_ylim(0, canvas_size[0])

        n_col = len(map_mask) // n_row
        gs = gridspec.GridSpec(n_row, n_col)
        gs.update(wspace=0.025, hspace=0.05)
        for i in range(len(map_mask)):
            r = i // n_col
            c = i - r * n_col
            subax = plt.subplot(gs[r, c])
            subax.imshow(map_mask[i], origin="lower")
            subax.text(canvas_size[0] * 0.5, canvas_size[1] * 1.1, layer_names[i])
            subax.grid(False)

        return fig, fig.axes

    def get_map_geom(
        self,
        patch_box: Tuple[float, float, float, float],
        patch_angle: float,
        layer_names: List[str],
    ) -> List[Tuple[str, List[Geometry]]]:
        """
        Returns a list of geometries in the specified patch_box.
        These are unscaled, but aligned with the patch angle.
        :param patch_box: Patch box defined as [x_center, y_center, height, width].
        :param patch_angle: Patch orientation in degrees.
                            North-facing corresponds to 0.
        :param layer_names: A list of layer names to be extracted, or None for all non-geometric layers.
        :return: List of layer names and their corresponding geometries.
        """
        # If None, return all geometric layers.
        if layer_names is None:
            layer_names = self.map_api.non_geometric_layers

        # Get each layer name and geometry and store them in a list.
        map_geom = []
        for layer_name in layer_names:
            layer_geom = self._get_layer_geom(patch_box, patch_angle, layer_name)
            if layer_geom is None:
                continue
            map_geom.append((layer_name, layer_geom))

        return map_geom

    def map_geom_to_mask(
        self,
        map_geom: List[Tuple[str, List[Geometry]]],
        local_box: Tuple[float, float, float, float],
        canvas_size: Tuple[int, int],
    ) -> np.ndarray:
        """
        Return list of map mask layers of the specified patch.
        :param map_geom: List of layer names and their corresponding geometries.
        :param local_box: The local patch box defined as (x_center, y_center, height, width), where typically
            x_center = y_center = 0.
        :param canvas_size: Size of the output mask (h, w).
        :return: Stacked numpy array of size [c x h x w] with c channels and the same height/width as the canvas.
        """
        # Get each layer mask and stack them into a numpy tensor.
        map_mask = []
        for layer_name, layer_geom in map_geom:
            layer_mask = self._layer_geom_to_mask(
                layer_name, layer_geom, local_box, canvas_size
            )
            if layer_mask is not None:
                map_mask.append(layer_mask)

        return np.array(map_mask)

    def get_map_mask(
        self,
        patch_box: Optional[Tuple[float, float, float, float]],
        patch_angle: float,
        layer_names: List[str] = None,
        canvas_size: Tuple[int, int] = (100, 100),
    ) -> np.ndarray:
        """
        Return list of map mask layers of the specified patch.
        :param patch_box: Patch box defined as [x_center, y_center, height, width]. If None, this plots the entire map.
        :param patch_angle: Patch orientation in degrees. North-facing corresponds to 0.
        :param layer_names: A list of layer names to be extracted, or None for all non-geometric layers.
        :param canvas_size: Size of the output mask (h, w). If None, we use the default resolution of 10px/m.
        :return: Stacked numpy array of size [c x h x w] with c channels and the same width/height as the canvas.
        """
        # For some combination of parameters, we need to know the size of the current map.
        if self.map_api.map_name == "singapore-onenorth":
            map_dims = [1585.6, 2025.0]
        elif self.map_api.map_name == "singapore-hollandvillage":
            map_dims = [2808.3, 2922.9]
        elif self.map_api.map_name == "singapore-queenstown":
            map_dims = [3228.6, 3687.1]
        elif self.map_api.map_name == "boston-seaport":
            map_dims = [2979.5, 2118.1]
        else:
            raise Exception("Error: Invalid map!")

        # If None, return the entire map.
        if patch_box is None:
            patch_box = [map_dims[0] / 2, map_dims[1] / 2, map_dims[1], map_dims[0]]

        # If None, return all geometric layers.
        if layer_names is None:
            layer_names = self.map_api.non_geometric_layers

        # If None, return the specified patch in the original scale of 10px/m.
        if canvas_size is None:
            map_scale = 10
            canvas_size = np.array((patch_box[2], patch_box[3])) * map_scale
            canvas_size = tuple(np.round(canvas_size).astype(np.int32))

        # Get geometry of each layer.
        map_geom = self.get_map_geom(patch_box, patch_angle, layer_names)

        # Convert geometry of each layer into mask and stack them into a numpy tensor.
        # Convert the patch box from global coordinates to local coordinates by setting the center to (0, 0).
        local_box = (0.0, 0.0, patch_box[2], patch_box[3])
        map_mask = self.map_geom_to_mask(map_geom, local_box, canvas_size)
        assert np.all(map_mask.shape[1:] == canvas_size)

        return map_mask

    def render_record(
        self,
        layer_name: str,
        token: str,
        alpha: float = 0.5,
        figsize: Union[None, float, Tuple[float, float]] = None,
        other_layers: List[str] = None,
        bitmap: Optional[BitMap] = None,
    ) -> Tuple[Figure, Tuple[Axes, Axes]]:
        """
        Render a single map record.
        By default will also render 3 layers which are `drivable_area`, `lane`, and `walkway` unless specified by
        `other_layers`.
        :param layer_name: Name of the layer that we are interested in.
        :param token: Token of the record that you want to render.
        :param alpha: The opacity of each layer that gets rendered.
        :param figsize: Size of the whole figure.
        :param other_layers: What other layers to render aside from the one specified in `layer_name`.
        :param bitmap: Optional BitMap object to render below the other map layers.
        :return: The matplotlib figure and axes of the rendered layers.
        """
        if other_layers is None:
            other_layers = list(self.representative_layers)

        for other_layer in other_layers:
            if other_layer not in self.map_api.non_geometric_layers:
                raise ValueError("{} is not a non geometric layer".format(layer_name))

        x1, y1, x2, y2 = self.map_api.get_bounds(layer_name, token)

        local_width = x2 - x1
        local_height = y2 - y1
        assert local_height > 0, "Error: Map has 0 height!"
        local_aspect_ratio = local_width / local_height

        # We obtained the values 0.65 and 0.66 by trials.
        fig = plt.figure(figsize=self._get_figsize(figsize))
        global_ax = fig.add_axes([0, 0, 0.65, 0.65 / self.canvas_aspect_ratio])
        local_ax = fig.add_axes(
            [0.66, 0.66 / self.canvas_aspect_ratio, 0.34, 0.34 / local_aspect_ratio]
        )

        # To make sure the sequence of the layer overlays is always consistent after typesetting set().
        random.seed("nutonomy")

        if bitmap is not None:
            bitmap.render(self.map_api.canvas_edge, global_ax)
            bitmap.render(self.map_api.canvas_edge, local_ax)

        layer_names = other_layers + [layer_name]
        layer_names = list(set(layer_names))

        for layer in layer_names:
            self._render_layer(global_ax, layer, alpha)

        for layer in layer_names:
            self._render_layer(local_ax, layer, alpha)

        if layer_name == "drivable_area":
            # Bad output aesthetically if we add spacing between the objects and the axes for drivable area.
            local_ax_xlim = (x1, x2)
            local_ax_ylim = (y1, y2)
        else:
            # Add some spacing between the object and the axes.
            local_ax_xlim = (x1 - local_width / 3, x2 + local_width / 3)
            local_ax_ylim = (y1 - local_height / 3, y2 + local_height / 3)

            # Draws the rectangular patch on the local_ax.
            local_ax.add_patch(
                Rectangle(
                    (x1, y1),
                    local_width,
                    local_height,
                    linestyle="-.",
                    color="red",
                    fill=False,
                    lw=2,
                )
            )

        local_ax.set_xlim(*local_ax_xlim)
        local_ax.set_ylim(*local_ax_ylim)
        local_ax.set_title("Local View")

        global_ax.set_xlim(self.canvas_min_x, self.canvas_max_x)
        global_ax.set_ylim(self.canvas_min_y, self.canvas_max_y)
        global_ax.set_title("Global View")
        global_ax.legend()

        # Adds the zoomed in effect to the plot.
        mark_inset(global_ax, local_ax, loc1=2, loc2=4)

        return fig, (global_ax, local_ax)

    def render_layers(
        self,
        layer_names: List[str],
        alpha: float,
        figsize: Union[None, float, Tuple[float, float]],
        tokens: List[str] = None,
        bitmap: Optional[BitMap] = None,
    ) -> Tuple[Figure, Axes]:
        """
        Render a list of layers.
        :param layer_names: A list of layer names.
        :param alpha: The opacity of each layer.
        :param figsize: Size of the whole figure.
        :param tokens: Optional list of tokens to render. None means all tokens are rendered.
        :param bitmap: Optional BitMap object to render below the other map layers.
        :return: The matplotlib figure and axes of the rendered layers.
        """
        fig = plt.figure(figsize=self._get_figsize(figsize))
        ax = fig.add_axes([0, 0, 1, 1 / self.canvas_aspect_ratio])

        ax.set_xlim(self.canvas_min_x, self.canvas_max_x)
        ax.set_ylim(self.canvas_min_y, self.canvas_max_y)

        if bitmap is not None:
            bitmap.render(self.map_api.canvas_edge, ax)

        layer_names = list(set(layer_names))
        for layer_name in layer_names:
            self._render_layer(ax, layer_name, alpha, tokens)

        ax.legend()

        return fig, ax

    def render_map_patch(
        self,
        box_coords: Tuple[float, float, float, float],
        layer_names: List[str] = None,
        alpha: float = 0.5,
        figsize: Tuple[float, float] = (15, 15),
        render_egoposes_range: bool = True,
        render_legend: bool = True,
        bitmap: Optional[BitMap] = None,
    ) -> Tuple[Figure, Axes]:
        """
        Renders a rectangular patch specified by `box_coords`. By default renders all layers.
        :param box_coords: The rectangular patch coordinates (x_min, y_min, x_max, y_max).
        :param layer_names: All the non geometric layers that we want to render.
        :param alpha: The opacity of each layer.
        :param figsize: Size of the whole figure.
        :param render_egoposes_range: Whether to render a rectangle around all ego poses.
        :param render_legend: Whether to render the legend of map layers.
        :param bitmap: Optional BitMap object to render below the other map layers.
        :return: The matplotlib figure and axes of the rendered layers.
        """
        x_min, y_min, x_max, y_max = box_coords

        if layer_names is None:
            layer_names = self.map_api.non_geometric_layers

        fig = plt.figure(figsize=figsize)

        local_width = x_max - x_min
        local_height = y_max - y_min
        assert local_height > 0, "Error: Map patch has 0 height!"
        local_aspect_ratio = local_width / local_height

        ax = fig.add_axes([0, 0, 1, 1 / local_aspect_ratio])

        if bitmap is not None:
            bitmap.render(self.map_api.canvas_edge, ax)

        for layer_name in layer_names:
            self._render_layer(ax, layer_name, alpha)

        x_margin = np.minimum(local_width / 4, 50)
        y_margin = np.minimum(local_height / 4, 10)
        ax.set_xlim(x_min - x_margin, x_max + x_margin)
        ax.set_ylim(y_min - y_margin, y_max + y_margin)

        if render_egoposes_range:
            ax.add_patch(
                Rectangle(
                    (x_min, y_min),
                    local_width,
                    local_height,
                    fill=False,
                    linestyle="-.",
                    color="red",
                    lw=2,
                )
            )
            ax.text(
                x_min + local_width / 100,
                y_min + local_height / 2,
                "%g m" % local_height,
                fontsize=14,
                weight="bold",
            )
            ax.text(
                x_min + local_width / 2,
                y_min + local_height / 100,
                "%g m" % local_width,
                fontsize=14,
                weight="bold",
            )

        if render_legend:
            ax.legend(frameon=True, loc="upper right")

        return fig, ax

    def render_map_in_image(
        self,
        nusc: NuScenes,
        sample_token: str,
        camera_channel: str = "CAM_FRONT",
        alpha: float = 0.3,
        patch_radius: float = 10000,
        min_polygon_area: float = 1000,
        render_behind_cam: bool = True,
        render_outside_im: bool = True,
        layer_names: List[str] = None,
        verbose: bool = True,
        out_path: str = None,
    ) -> Tuple[Figure, Axes]:
        """
        Render a nuScenes camera image and overlay the polygons for the specified map layers.
        Note that the projections are not always accurate as the localization is in 2d.
        :param nusc: The NuScenes instance to load the image from.
        :param sample_token: The image's corresponding sample_token.
        :param camera_channel: Camera channel name, e.g. 'CAM_FRONT'.
        :param alpha: The transparency value of the layers to render in [0, 1].
        :param patch_radius: The radius in meters around the ego car in which to select map records.
        :param min_polygon_area: Minimum area a polygon needs to have to be rendered.
        :param render_behind_cam: Whether to render polygons where any point is behind the camera.
        :param render_outside_im: Whether to render polygons where any point is outside the image.
        :param layer_names: The names of the layers to render, e.g. ['lane'].
            If set to None, the recommended setting will be used.
        :param verbose: Whether to print to stdout.
        :param out_path: Optional path to save the rendered figure to disk.
        """
        near_plane = 1e-8

        if verbose:
            print(
                "Warning: Note that the projections are not always accurate as the localization is in 2d."
            )

        # Default layers.
        if layer_names is None:
            layer_names = [
                "road_segment",
                "lane",
                "ped_crossing",
                "walkway",
                "stop_line",
                "carpark_area",
            ]

        # Check layers whether we can render them.
        for layer_name in layer_names:
            assert layer_name in self.map_api.non_geometric_polygon_layers, (
                "Error: Can only render non-geometry polygons: %s" % layer_names
            )

        # Check that NuScenesMap was loaded for the correct location.
        sample_record = nusc.get("sample", sample_token)
        scene_record = nusc.get("scene", sample_record["scene_token"])
        log_record = nusc.get("log", scene_record["log_token"])
        log_location = log_record["location"]
        assert (
            self.map_api.map_name == log_location
        ), "Error: NuScenesMap loaded for location %s, should be %s!" % (
            self.map_api.map_name,
            log_location,
        )

        # Grab the front camera image and intrinsics.
        cam_token = sample_record["data"][camera_channel]
        cam_record = nusc.get("sample_data", cam_token)
        cam_path = nusc.get_sample_data_path(cam_token)
        im = Image.open(cam_path)
        im_size = im.size
        cs_record = nusc.get("calibrated_sensor", cam_record["calibrated_sensor_token"])
        cam_intrinsic = np.array(cs_record["camera_intrinsic"])

        # Retrieve the current map.
        poserecord = nusc.get("ego_pose", cam_record["ego_pose_token"])
        ego_pose = poserecord["translation"]
        box_coords = (
            ego_pose[0] - patch_radius,
            ego_pose[1] - patch_radius,
            ego_pose[0] + patch_radius,
            ego_pose[1] + patch_radius,
        )
        records_in_patch = self.get_records_in_patch(
            box_coords, layer_names, "intersect"
        )

        # Init axes.
        fig = plt.figure(figsize=(9, 16))
        ax = fig.add_axes([0, 0, 1, 1])
        ax.set_xlim(0, im_size[0])
        ax.set_ylim(0, im_size[1])
        ax.imshow(im)

        # Retrieve and render each record.
        for layer_name in layer_names:
            for token in records_in_patch[layer_name]:
                record = self.map_api.get(layer_name, token)
                if layer_name == "drivable_area":
                    polygon_tokens = record["polygon_tokens"]
                else:
                    polygon_tokens = [record["polygon_token"]]

                for polygon_token in polygon_tokens:
                    polygon = self.map_api.extract_polygon(polygon_token)

                    # Convert polygon nodes to pointcloud with 0 height.
                    points = np.array(polygon.exterior.xy)
                    points = np.vstack((points, np.zeros((1, points.shape[1]))))

                    # Transform into the ego vehicle frame for the timestamp of the image.
                    points = points - np.array(poserecord["translation"]).reshape(
                        (-1, 1)
                    )
                    points = np.dot(
                        Quaternion(poserecord["rotation"]).rotation_matrix.T, points
                    )

                    # Transform into the camera.
                    points = points - np.array(cs_record["translation"]).reshape(
                        (-1, 1)
                    )
                    points = np.dot(
                        Quaternion(cs_record["rotation"]).rotation_matrix.T, points
                    )

                    # Remove points that are partially behind the camera.
                    depths = points[2, :]
                    behind = depths < near_plane
                    if np.all(behind):
                        continue

                    if render_behind_cam:
                        # Perform clipping on polygons that are partially behind the camera.
                        points = NuScenesMapExplorer._clip_points_behind_camera(
                            points, near_plane
                        )
                    elif np.any(behind):
                        # Otherwise ignore any polygon that is partially behind the camera.
                        continue

                    # Ignore polygons with less than 3 points after clipping.
                    if len(points) == 0 or points.shape[1] < 3:
                        continue

                    # Take the actual picture (matrix multiplication with camera-matrix + renormalization).
                    points = view_points(points, cam_intrinsic, normalize=True)

                    # Skip polygons where all points are outside the image.
                    # Leave a margin of 1 pixel for aesthetic reasons.
                    inside = np.ones(points.shape[1], dtype=bool)
                    inside = np.logical_and(inside, points[0, :] > 1)
                    inside = np.logical_and(inside, points[0, :] < im.size[0] - 1)
                    inside = np.logical_and(inside, points[1, :] > 1)
                    inside = np.logical_and(inside, points[1, :] < im.size[1] - 1)
                    if render_outside_im:
                        if np.all(np.logical_not(inside)):
                            continue
                    else:
                        if np.any(np.logical_not(inside)):
                            continue

                    points = points[:2, :]
                    points = [(p0, p1) for (p0, p1) in zip(points[0], points[1])]
                    polygon_proj = Polygon(points)

                    # Filter small polygons
                    if polygon_proj.area < min_polygon_area:
                        continue

                    label = layer_name
                    ax.add_patch(
                        descartes.PolygonPatch(
                            polygon_proj,
                            fc=self.color_map[layer_name],
                            alpha=alpha,
                            label=label,
                        )
                    )

        # Display the image.
        plt.axis("off")
        ax.invert_yaxis()

        if out_path is not None:
            plt.tight_layout()
            plt.savefig(out_path, bbox_inches="tight", pad_inches=0)

        return fig, ax

    @staticmethod
    def points_transform(
        points,
        poserecord,
        cs_record,
        cam_intrinsic,
        im_size,
        near_plane=1e-8,
        render_behind_cam=True,
        render_outside_im=True,
    ):
        points = np.vstack((points, np.zeros((1, points.shape[1]))))

        # Transform into the ego vehicle frame for the timestamp of the image.
        points = points - np.array(poserecord["translation"]).reshape((-1, 1))
        points = np.dot(Quaternion(poserecord["rotation"]).rotation_matrix.T, points)

        # Transform into the camera.
        points = points - np.array(cs_record["translation"]).reshape((-1, 1))
        points = np.dot(Quaternion(cs_record["rotation"]).rotation_matrix.T, points)

        # Remove points that are partially behind the camera.
        depths = points[2, :]
        behind = depths < near_plane
        if np.all(behind):
            return None

        if render_behind_cam:
            # Perform clipping on polygons that are partially behind the camera.
            points = NuScenesMapExplorer._clip_points_behind_camera(points, near_plane)

        elif np.any(behind):
            # Otherwise ignore any polygon that is partially behind the camera.
            return None

        # Take the actual picture (matrix multiplication with camera-matrix + renormalization).
        points = view_points(points, cam_intrinsic, normalize=True)

        # Skip polygons where all points are outside the image.
        # Leave a margin of 1 pixel for aesthetic reasons.
        inside = np.ones(points.shape[1], dtype=bool)
        inside = np.logical_and(inside, points[0, :] > 1)
        inside = np.logical_and(inside, points[0, :] < im_size[0] - 1)
        inside = np.logical_and(inside, points[1, :] > 1)
        inside = np.logical_and(inside, points[1, :] < im_size[1] - 1)

        if render_outside_im:
            if np.all(np.logical_not(inside)):
                return None
        else:
            if np.any(np.logical_not(inside)):
                return None

        # points = points[:, inside]

        # Ignore polygons with less than 3 points after clipping.
        if len(points) == 0 or points.shape[1] < 3:
            return None

        points = points[:2, :]
        points = [(p0, p1) for (p0, p1) in zip(points[0], points[1])]
        return points

    def get_map_mask_in_image(
        self,
        nusc: NuScenes,
        sample_token: str,
        camera_channel: str = "CAM_FRONT",
        alpha: float = 0.3,
        patch_radius: float = 10000,
        min_polygon_area: float = 1000,
        render_behind_cam: bool = True,
        render_outside_im: bool = True,
        layer_names: List[str] = None,
        verbose: bool = False,
        out_path: str = None,
    ) -> np.ndarray:
        """
        Render a nuScenes camera image and overlay the polygons for the specified map layers.
        Note that the projections are not always accurate as the localization is in 2d.
        :param nusc: The NuScenes instance to load the image from.
        :param sample_token: The image's corresponding sample_token.
        :param camera_channel: Camera channel name, e.g. 'CAM_FRONT'.
        :param alpha: The transparency value of the layers to render in [0, 1].
        :param patch_radius: The radius in meters around the ego car in which to select map records.
        :param min_polygon_area: Minimum area a polygon needs to have to be rendered.
        :param render_behind_cam: Whether to render polygons where any point is behind the camera.
        :param render_outside_im: Whether to render polygons where any point is outside the image.
        :param layer_names: The names of the layers to render, e.g. ['lane'].
            If set to None, the recommended setting will be used.
        :param verbose: Whether to print to stdout.
        :param out_path: Optional path to save the rendered figure to disk.
        """
        near_plane = 1e-8
        if verbose:
            print(
                "Warning: Note that the projections are not always accurate as the localization is in 2d."
            )

        # Default layers.
        if layer_names is None:
            layer_names = [
                "road_segment",
                "lane",
                "ped_crossing",
                "walkway",
                "stop_line",
                "carpark_area",
            ]

        # # Check layers whether we can render them.
        # for layer_name in layer_names:
        #     assert layer_name in self.map_api.non_geometric_polygon_layers, \
        #         'Error: Can only render non-geometry polygons: %s' % layer_names

        # Check that NuScenesMap was loaded for the correct location.
        sample_record = nusc.get("sample", sample_token)
        scene_record = nusc.get("scene", sample_record["scene_token"])
        log_record = nusc.get("log", scene_record["log_token"])
        log_location = log_record["location"]
        assert (
            self.map_api.map_name == log_location
        ), "Error: NuScenesMap loaded for location %s, should be %s!" % (
            self.map_api.map_name,
            log_location,
        )

        # Grab the front camera image and intrinsics.
        cam_token = sample_record["data"][camera_channel]
        cam_record = nusc.get("sample_data", cam_token)
        cam_path = nusc.get_sample_data_path(cam_token)
        im = Image.open(cam_path)
        im_size = im.size
        cs_record = nusc.get("calibrated_sensor", cam_record["calibrated_sensor_token"])
        cam_intrinsic = np.array(cs_record["camera_intrinsic"])

        # Retrieve the current map.
        poserecord = nusc.get("ego_pose", cam_record["ego_pose_token"])
        ego_pose = poserecord["translation"]
        box_coords = (
            ego_pose[0] - patch_radius,
            ego_pose[1] - patch_radius,
            ego_pose[0] + patch_radius,
            ego_pose[1] + patch_radius,
        )
        records_in_patch = self.get_records_in_patch(
            box_coords, layer_names, "intersect"
        )

        if out_path is not None:
            # Init axes.
            fig = plt.figure(figsize=(9, 16))
            ax = fig.add_axes([0, 0, 1, 1])
            ax.set_xlim(0, im_size[0])
            ax.set_ylim(0, im_size[1])
            ax.imshow(im)

        points_transform = partial(
            self.points_transform,
            poserecord=poserecord,
            cs_record=cs_record,
            cam_intrinsic=cam_intrinsic,
            near_plane=near_plane,
            im_size=im_size,
            render_behind_cam=render_behind_cam,
            render_outside_im=render_outside_im,
        )

        # Retrieve and render each record.
        map_geom = []
        for layer_name in layer_names:
            if layer_name in self.map_api.non_geometric_line_layers:
                line_list = []
                for token in records_in_patch[layer_name]:
                    record = self.map_api.get(layer_name, token)
                    line = self.map_api.extract_line(record["line_token"])
                    if line.is_empty:  # Skip lines without nodes.
                        continue
                    points = np.array(line.xy)
                    points = points_transform(points)
                    if points is None:
                        continue
                    line = LineString(points)
                    line_list.append(line)
                    # For visualize
                    if out_path is not None:
                        polygon = Polygon(points)
                        ax.add_patch(
                            descartes.PolygonPatch(
                                polygon,
                                fc=self.color_map[layer_name],
                                alpha=alpha,
                                label=layer_name,
                            )
                        )
                map_geom.append((layer_name, line_list))
            elif layer_name == "drivable_area":
                polygon_list = []
                for token in records_in_patch[layer_name]:
                    record = self.map_api.get(layer_name, token)
                    polygons = [
                        self.map_api.extract_polygon(polygon_token)
                        for polygon_token in record["polygon_tokens"]
                    ]
                    for polygon in polygons:
                        ex_points = np.array(polygon.exterior.xy)
                        ex_points = points_transform(ex_points)
                        if ex_points is None:
                            continue
                        interiors = []
                        for interior in polygon.interiors:
                            in_points = np.array(interior.xy)
                            in_points = points_transform(in_points)
                            if in_points is None:
                                continue
                            interiors.append(in_points)
                        polygon = Polygon(ex_points, interiors)
                        polygon = polygon.buffer(0.01)
                        if polygon.geom_type == "Polygon":
                            polygon = MultiPolygon([polygon])
                        # Filter small polygons
                        if polygon.area < min_polygon_area:
                            continue
                        polygon_list.append(polygon)
                        # For visualize
                        if out_path is not None:
                            ax.add_patch(
                                descartes.PolygonPatch(
                                    polygon,
                                    fc=self.color_map[layer_name],
                                    alpha=alpha,
                                    label=layer_name,
                                )
                            )
                map_geom.append((layer_name, polygon_list))
            else:
                polygon_list = []
                for token in records_in_patch[layer_name]:
                    record = self.map_api.get(layer_name, token)
                    polygon = self.map_api.extract_polygon(record["polygon_token"])
                    if polygon.is_valid:
                        if not polygon.is_empty:
                            ex_points = np.array(polygon.exterior.xy)
                            ex_points = points_transform(ex_points)
                            if ex_points is None:
                                continue
                            interiors = []
                            for interior in polygon.interiors:
                                in_points = np.array(interior.xy)
                                in_points = points_transform(in_points)
                                if in_points is None:
                                    continue
                                interiors.append(in_points)
                            polygon = Polygon(ex_points, interiors)
                            polygon = polygon.buffer(0.01)
                            if polygon.geom_type == "Polygon":
                                polygon = MultiPolygon([polygon])
                            # Filter small polygons
                            if polygon.area < min_polygon_area:
                                continue
                            polygon_list.append(polygon)
                            # For visualize
                            if out_path is not None:
                                ax.add_patch(
                                    descartes.PolygonPatch(
                                        polygon,
                                        fc=self.color_map[layer_name],
                                        alpha=alpha,
                                        label=layer_name,
                                    )
                                )
                map_geom.append((layer_name, polygon_list))

        # For visualize
        if out_path is not None:
            # Display the image.
            plt.axis("off")
            ax.invert_yaxis()
            plt.tight_layout()
            plt.savefig(out_path, bbox_inches="tight", pad_inches=0)
            plt.close()

        # Convert geometry of each layer into mask and stack them into a numpy tensor.
        # Convert the patch box from global coordinates to local coordinates by setting the center to (0, 0).
        local_box = (im_size[0] // 2, im_size[1] // 2, im_size[1], im_size[0])
        canvas_size = (im_size[1], im_size[0])
        img_mask = self.map_geom_to_mask(map_geom, local_box, canvas_size)
        assert np.all(img_mask.shape[1:] == canvas_size)
        return img_mask

    def render_egoposes_on_fancy_map(
        self,
        nusc: NuScenes,
        scene_tokens: List = None,
        verbose: bool = True,
        out_path: str = None,
        render_egoposes: bool = True,
        render_egoposes_range: bool = True,
        render_legend: bool = True,
        bitmap: Optional[BitMap] = None,
    ) -> Tuple[np.ndarray, Figure, Axes]:
        """
        Renders each ego pose of a list of scenes on the map (around 40 poses per scene).
        This method is heavily inspired by NuScenes.render_egoposes_on_map(), but uses the map expansion pack maps.
        Note that the maps are constantly evolving, whereas we only released a single snapshot of the data.
        Therefore for some scenes there is a bad fit between ego poses and maps.
        :param nusc: The NuScenes instance to load the ego poses from.
        :param scene_tokens: Optional list of scene tokens corresponding to the current map location.
        :param verbose: Whether to show status messages and progress bar.
        :param out_path: Optional path to save the rendered figure to disk.
        :param render_egoposes: Whether to render ego poses.
        :param render_egoposes_range: Whether to render a rectangle around all ego poses.
        :param render_legend: Whether to render the legend of map layers.
        :param bitmap: Optional BitMap object to render below the other map layers.
        :return: <np.float32: n, 2>. Returns a matrix with n ego poses in global map coordinates.
        """
        # Settings
        patch_margin = 2
        min_diff_patch = 30

        # Ids of scenes with a bad match between localization and map.
        scene_blacklist = [499, 515, 517]

        # Get logs by location.
        log_location = self.map_api.map_name
        log_tokens = [
            log["token"] for log in nusc.log if log["location"] == log_location
        ]
        assert len(log_tokens) > 0, (
            "Error: This split has 0 scenes for location %s!" % log_location
        )

        # Filter scenes.
        scene_tokens_location = [
            e["token"] for e in nusc.scene if e["log_token"] in log_tokens
        ]
        if scene_tokens is not None:
            scene_tokens_location = [
                t for t in scene_tokens_location if t in scene_tokens
            ]
        assert len(scene_tokens_location) > 0, (
            "Error: Found 0 valid scenes for location %s!" % log_location
        )

        map_poses = []
        if verbose:
            print("Adding ego poses to map...")
        for scene_token in tqdm(scene_tokens_location, disable=not verbose):
            # Check that the scene is from the correct location.
            scene_record = nusc.get("scene", scene_token)
            scene_name = scene_record["name"]
            scene_id = int(scene_name.replace("scene-", ""))
            log_record = nusc.get("log", scene_record["log_token"])
            assert (
                log_record["location"] == log_location
            ), "Error: The provided scene_tokens do not correspond to the provided map location!"

            # Print a warning if the localization is known to be bad.
            if verbose and scene_id in scene_blacklist:
                print(
                    "Warning: %s is known to have a bad fit between ego pose and map."
                    % scene_name
                )

            # For each sample in the scene, store the ego pose.
            sample_tokens = nusc.field2token("sample", "scene_token", scene_token)
            for sample_token in sample_tokens:
                sample_record = nusc.get("sample", sample_token)

                # Poses are associated with the sample_data. Here we use the lidar sample_data.
                sample_data_record = nusc.get(
                    "sample_data", sample_record["data"]["LIDAR_TOP"]
                )
                pose_record = nusc.get("ego_pose", sample_data_record["ego_pose_token"])

                # Calculate the pose on the map and append.
                map_poses.append(pose_record["translation"])

        # Check that ego poses aren't empty.
        assert len(map_poses) > 0, "Error: Found 0 ego poses. Please check the inputs."

        # Compute number of close ego poses.
        if verbose:
            print("Creating plot...")
        map_poses = np.vstack(map_poses)[:, :2]

        # Render the map patch with the current ego poses.
        min_patch = np.floor(map_poses.min(axis=0) - patch_margin)
        max_patch = np.ceil(map_poses.max(axis=0) + patch_margin)
        diff_patch = max_patch - min_patch
        if any(diff_patch < min_diff_patch):
            center_patch = (min_patch + max_patch) / 2
            diff_patch = np.maximum(diff_patch, min_diff_patch)
            min_patch = center_patch - diff_patch / 2
            max_patch = center_patch + diff_patch / 2
        my_patch = (min_patch[0], min_patch[1], max_patch[0], max_patch[1])
        fig, ax = self.render_map_patch(
            my_patch,
            self.map_api.non_geometric_layers,
            figsize=(10, 10),
            render_egoposes_range=render_egoposes_range,
            render_legend=render_legend,
            bitmap=bitmap,
        )

        # Plot in the same axis as the map.
        # Make sure these are plotted "on top".
        if render_egoposes:
            ax.scatter(
                map_poses[:, 0], map_poses[:, 1], s=20, c="k", alpha=1.0, zorder=2
            )
        plt.axis("off")

        if out_path is not None:
            plt.savefig(out_path, bbox_inches="tight", pad_inches=0)

        return map_poses, fig, ax

    def render_next_roads(
        self,
        x: float,
        y: float,
        alpha: float = 0.5,
        figsize: Union[None, float, Tuple[float, float]] = None,
        bitmap: Optional[BitMap] = None,
    ) -> Tuple[Figure, Axes]:
        """
        Renders the possible next roads from a point of interest.
        :param x: x coordinate of the point of interest.
        :param y: y coordinate of the point of interest.
        :param alpha: The opacity of each layer that gets rendered.
        :param figsize: Size of the whole figure.
        :param bitmap: Optional BitMap object to render below the other map layers.
        """
        # Get next roads.
        next_roads = self.map_api.get_next_roads(x, y)
        layer_names = []
        tokens = []
        for layer_name, layer_tokens in next_roads.items():
            if len(layer_tokens) > 0:
                layer_names.append(layer_name)
                tokens.extend(layer_tokens)

        # Render them.
        fig, ax = self.render_layers(
            layer_names, alpha, figsize, tokens=tokens, bitmap=bitmap
        )

        # Render current location with an x.
        ax.plot(x, y, "x", markersize=12, color="red")

        return fig, ax

    @staticmethod
    def _clip_points_behind_camera(points, near_plane: float):
        """
        Perform clipping on polygons that are partially behind the camera.
        This method is necessary as the projection does not work for points behind the camera.
        Hence we compute the line between the point and the camera and follow that line until we hit the near plane of
        the camera. Then we use that point.
        :param points: <np.float32: 3, n> Matrix of points, where each point (x, y, z) is along each column.
        :param near_plane: If we set the near_plane distance of the camera to 0 then some points will project to
            infinity. Therefore we need to clip these points at the near plane.
        :return: The clipped version of the polygon. This may have fewer points than the original polygon if some lines
            were entirely behind the polygon.
        """
        points_clipped = []
        # Loop through each line on the polygon.
        # For each line where exactly 1 endpoints is behind the camera, move the point along the line until
        # it hits the near plane of the camera (clipping).
        assert points.shape[0] == 3
        point_count = points.shape[1]
        for line_1 in range(point_count):
            line_2 = (line_1 + 1) % point_count
            point_1 = points[:, line_1]
            point_2 = points[:, line_2]
            z_1 = point_1[2]
            z_2 = point_2[2]

            if z_1 >= near_plane and z_2 >= near_plane:
                # Both points are in front.
                # Add both points unless the first is already added.
                if len(points_clipped) == 0 or all(points_clipped[-1] != point_1):
                    points_clipped.append(point_1)
                points_clipped.append(point_2)
            elif z_1 < near_plane and z_2 < near_plane:
                # Both points are in behind.
                # Don't add anything.
                continue
            else:
                # One point is in front, one behind.
                # By convention pointA is behind the camera and pointB in front.
                if z_1 <= z_2:
                    point_a = points[:, line_1]
                    point_b = points[:, line_2]
                else:
                    point_a = points[:, line_2]
                    point_b = points[:, line_1]
                z_a = point_a[2]
                z_b = point_b[2]

                # Clip line along near plane.
                pointdiff = point_b - point_a
                alpha = (near_plane - z_b) / (z_a - z_b)
                clipped = point_a + (1 - alpha) * pointdiff
                assert np.abs(clipped[2] - near_plane) < 1e-6

                # Add the first point (if valid and not duplicate), the clipped point and the second point (if valid).
                if z_1 >= near_plane and (
                    len(points_clipped) == 0 or all(points_clipped[-1] != point_1)
                ):
                    points_clipped.append(point_1)
                points_clipped.append(clipped)
                if z_2 >= near_plane:
                    points_clipped.append(point_2)

        points_clipped = np.array(points_clipped).transpose()
        return points_clipped

    def get_records_in_patch(
        self,
        box_coords: Tuple[float, float, float, float],
        layer_names: List[str] = None,
        mode: str = "intersect",
    ) -> Dict[str, List[str]]:
        """
        Get all the record token that intersects or within a particular rectangular patch.
        :param box_coords: The rectangular patch coordinates (x_min, y_min, x_max, y_max).
        :param layer_names: Names of the layers that we want to retrieve in a particular patch.
            By default will always look for all non geometric layers.
        :param mode: "intersect" will return all non geometric records that intersects the patch,
            "within" will return all non geometric records that are within the patch.
        :return: Dictionary of layer_name - tokens pairs.
        """
        if mode not in ["intersect", "within"]:
            raise ValueError(
                "Mode {} is not valid, choice=('intersect', 'within')".format(mode)
            )

        if layer_names is None:
            layer_names = self.map_api.non_geometric_layers

        records_in_patch = dict()
        for layer_name in layer_names:
            layer_records = []
            for record in getattr(self.map_api, layer_name):
                token = record["token"]
                if self.is_record_in_patch(layer_name, token, box_coords, mode):
                    layer_records.append(token)

            records_in_patch.update({layer_name: layer_records})

        return records_in_patch

    def is_record_in_patch(
        self,
        layer_name: str,
        token: str,
        box_coords: Tuple[float, float, float, float],
        mode: str = "intersect",
    ) -> bool:
        """
        Query whether a particular record is in a rectangular patch.
        :param layer_name: The layer name of the record.
        :param token: The record token.
        :param box_coords: The rectangular patch coordinates (x_min, y_min, x_max, y_max).
        :param mode: "intersect" means it will return True if the geometric object intersects the patch and False
        otherwise, "within" will return True if the geometric object is within the patch and False otherwise.
        :return: Boolean value on whether a particular record intersects or is within a particular patch.
        """
        if mode not in ["intersect", "within"]:
            raise ValueError(
                "Mode {} is not valid, choice=('intersect', 'within')".format(mode)
            )

        if layer_name in self.map_api.lookup_polygon_layers:
            return self._is_polygon_record_in_patch(token, layer_name, box_coords, mode)
        elif layer_name in self.map_api.non_geometric_line_layers:
            return self._is_line_record_in_patch(token, layer_name, box_coords, mode)
        else:
            raise ValueError("{} is not a valid layer".format(layer_name))

    def layers_on_point(
        self, x: float, y: float, layer_names: List[str] = None
    ) -> Dict[str, str]:
        """
        Returns all the polygonal layers that a particular point is on.
        :param x: x coordinate of the point of interest.
        :param y: y coordinate of the point of interest.
        :param layer_names: The names of the layers to search for.
        :return: All the polygonal layers that a particular point is on.
        """
        # Default option.
        if layer_names is None:
            layer_names = self.map_api.non_geometric_polygon_layers

        layers_on_point = dict()
        for layer_name in layer_names:
            layers_on_point.update({layer_name: self.record_on_point(x, y, layer_name)})

        return layers_on_point

    def record_on_point(self, x: float, y: float, layer_name: str) -> str:
        """
        Query what record of a layer a particular point is on.
        :param x: x coordinate of the point of interest.
        :param y: y coordinate of the point of interest.
        :param layer_name: The non geometric polygonal layer name that we are interested in.
        :return: The first token of a layer a particular point is on or '' if no layer is found.
        """
        if layer_name not in self.map_api.non_geometric_polygon_layers:
            raise ValueError("{} is not a polygon layer".format(layer_name))

        point = Point(x, y)
        records = getattr(self.map_api, layer_name)

        if layer_name == "drivable_area":
            for record in records:
                polygons = [
                    self.map_api.extract_polygon(polygon_token)
                    for polygon_token in record["polygon_tokens"]
                ]
                for polygon in polygons:
                    if point.within(polygon):
                        return record["token"]
                    else:
                        pass
        else:
            for record in records:
                polygon = self.map_api.extract_polygon(record["polygon_token"])
                if point.within(polygon):
                    return record["token"]
                else:
                    pass

        # If nothing is found, return an empty string.
        return ""

    def extract_polygon(self, polygon_token: str) -> Polygon:
        """
        Construct a shapely Polygon object out of a polygon token.
        :param polygon_token: The token of the polygon record.
        :return: The polygon wrapped in a shapely Polygon object.
        """
        polygon_record = self.map_api.get("polygon", polygon_token)

        exterior_coords = [
            (self.map_api.get("node", token)["x"], self.map_api.get("node", token)["y"])
            for token in polygon_record["exterior_node_tokens"]
        ]

        interiors = []
        for hole in polygon_record["holes"]:
            interior_coords = [
                (
                    self.map_api.get("node", token)["x"],
                    self.map_api.get("node", token)["y"],
                )
                for token in hole["node_tokens"]
            ]
            if len(interior_coords) > 0:  # Add only non-empty holes.
                interiors.append(interior_coords)

        return Polygon(exterior_coords, interiors)

    def extract_line(self, line_token: str) -> LineString:
        """
        Construct a shapely LineString object out of a line token.
        :param line_token: The token of the line record.
        :return: The line wrapped in a LineString object.
        """
        line_record = self.map_api.get("line", line_token)
        line_nodes = [
            (self.map_api.get("node", token)["x"], self.map_api.get("node", token)["y"])
            for token in line_record["node_tokens"]
        ]

        return LineString(line_nodes)

    def get_bounds(
        self, layer_name: str, token: str
    ) -> Tuple[float, float, float, float]:
        """
        Get the bounds of the geometric object that corresponds to a non geometric record.
        :param layer_name: Name of the layer that we are interested in.
        :param token: Token of the record.
        :return: min_x, min_y, max_x, max_y of the line representation.
        """
        if layer_name in self.map_api.non_geometric_polygon_layers:
            return self._get_polygon_bounds(layer_name, token)
        elif layer_name in self.map_api.non_geometric_line_layers:
            return self._get_line_bounds(layer_name, token)
        else:
            raise ValueError("{} is not a valid layer".format(layer_name))

    def _get_polygon_bounds(
        self, layer_name: str, token: str
    ) -> Tuple[float, float, float, float]:
        """
        Get the extremities of the polygon object that corresponds to a non geometric record.
        :param layer_name: Name of the layer that we are interested in.
        :param token: Token of the record.
        :return: min_x, min_y, max_x, max_y of of the polygon or polygons (for drivable_area) representation.
        """
        if layer_name not in self.map_api.non_geometric_polygon_layers:
            raise ValueError(
                "{} is not a record with polygon representation".format(token)
            )

        record = self.map_api.get(layer_name, token)

        if layer_name == "drivable_area":
            polygons = [
                self.map_api.get("polygon", polygon_token)
                for polygon_token in record["polygon_tokens"]
            ]
            exterior_node_coords = []

            for polygon in polygons:
                nodes = [
                    self.map_api.get("node", node_token)
                    for node_token in polygon["exterior_node_tokens"]
                ]
                node_coords = [(node["x"], node["y"]) for node in nodes]
                exterior_node_coords.extend(node_coords)

            exterior_node_coords = np.array(exterior_node_coords)
        else:
            exterior_nodes = [
                self.map_api.get("node", token)
                for token in record["exterior_node_tokens"]
            ]
            exterior_node_coords = np.array(
                [(node["x"], node["y"]) for node in exterior_nodes]
            )

        xs = exterior_node_coords[:, 0]
        ys = exterior_node_coords[:, 1]

        x2 = xs.max()
        x1 = xs.min()
        y2 = ys.max()
        y1 = ys.min()

        return x1, y1, x2, y2

    def _get_line_bounds(
        self, layer_name: str, token: str
    ) -> Tuple[float, float, float, float]:
        """
        Get the bounds of the line object that corresponds to a non geometric record.
        :param layer_name: Name of the layer that we are interested in.
        :param token: Token of the record.
        :return: min_x, min_y, max_x, max_y of of the line representation.
        """
        if layer_name not in self.map_api.non_geometric_line_layers:
            raise ValueError(
                "{} is not a record with line representation".format(token)
            )

        record = self.map_api.get(layer_name, token)
        nodes = [
            self.map_api.get("node", node_token) for node_token in record["node_tokens"]
        ]
        node_coords = [(node["x"], node["y"]) for node in nodes]
        node_coords = np.array(node_coords)

        xs = node_coords[:, 0]
        ys = node_coords[:, 1]

        x2 = xs.max()
        x1 = xs.min()
        y2 = ys.max()
        y1 = ys.min()

        return x1, y1, x2, y2

    def _is_polygon_record_in_patch(
        self,
        token: str,
        layer_name: str,
        box_coords: Tuple[float, float, float, float],
        mode: str = "intersect",
    ) -> bool:
        """
        Query whether a particular polygon record is in a rectangular patch.
        :param layer_name: The layer name of the record.
        :param token: The record token.
        :param box_coords: The rectangular patch coordinates (x_min, y_min, x_max, y_max).
        :param mode: "intersect" means it will return True if the geometric object intersects the patch and False
        otherwise, "within" will return True if the geometric object is within the patch and False otherwise.
        :return: Boolean value on whether a particular polygon record intersects or is within a particular patch.
        """
        if layer_name not in self.map_api.lookup_polygon_layers:
            raise ValueError("{} is not a polygonal layer".format(layer_name))

        x_min, y_min, x_max, y_max = box_coords
        record = self.map_api.get(layer_name, token)
        rectangular_patch = box(x_min, y_min, x_max, y_max)

        if layer_name == "drivable_area":
            polygons = [
                self.map_api.extract_polygon(polygon_token)
                for polygon_token in record["polygon_tokens"]
            ]
            geom = MultiPolygon(polygons)
        else:
            geom = self.map_api.extract_polygon(record["polygon_token"])

        if mode == "intersect":
            return geom.intersects(rectangular_patch)
        elif mode == "within":
            return geom.within(rectangular_patch)

    def _is_line_record_in_patch(
        self,
        token: str,
        layer_name: str,
        box_coords: Tuple[float, float, float, float],
        mode: str = "intersect",
    ) -> bool:
        """
        Query whether a particular line record is in a rectangular patch.
        :param layer_name: The layer name of the record.
        :param token: The record token.
        :param box_coords: The rectangular patch coordinates (x_min, y_min, x_max, y_max).
        :param mode: "intersect" means it will return True if the geometric object intersects the patch and False
        otherwise, "within" will return True if the geometric object is within the patch and False otherwise.
        :return: Boolean value on whether a particular line  record intersects or is within a particular patch.
        """
        if layer_name not in self.map_api.non_geometric_line_layers:
            raise ValueError("{} is not a line layer".format(layer_name))

        # Retrieve nodes of this line.
        record = self.map_api.get(layer_name, token)
        node_recs = [
            self.map_api.get("node", node_token) for node_token in record["node_tokens"]
        ]
        node_coords = [[node["x"], node["y"]] for node in node_recs]
        node_coords = np.array(node_coords)

        # A few lines in Queenstown have zero nodes. In this case we return False.
        if len(node_coords) == 0:
            return False

        # Check that nodes fall inside the path.
        x_min, y_min, x_max, y_max = box_coords
        cond_x = np.logical_and(node_coords[:, 0] < x_max, node_coords[:, 0] > x_min)
        cond_y = np.logical_and(node_coords[:, 1] < y_max, node_coords[:, 1] > y_min)
        cond = np.logical_and(cond_x, cond_y)
        if mode == "intersect":
            return np.any(cond)
        elif mode == "within":
            return np.all(cond)

    def _render_layer(
        self, ax: Axes, layer_name: str, alpha: float, tokens: List[str] = None
    ) -> None:
        """
        Wrapper method that renders individual layers on an axis.
        :param ax: The matplotlib axes where the layer will get rendered.
        :param layer_name: Name of the layer that we are interested in.
        :param alpha: The opacity of the layer to be rendered.
        :param tokens: Optional list of tokens to render. None means all tokens are rendered.
        """
        if layer_name in self.map_api.non_geometric_polygon_layers:
            self._render_polygon_layer(ax, layer_name, alpha, tokens)
        elif layer_name in self.map_api.non_geometric_line_layers:
            self._render_line_layer(ax, layer_name, alpha, tokens)
        else:
            raise ValueError("{} is not a valid layer".format(layer_name))

    def _render_polygon_layer(
        self, ax: Axes, layer_name: str, alpha: float, tokens: List[str] = None
    ) -> None:
        """
        Renders an individual non-geometric polygon layer on an axis.
        :param ax: The matplotlib axes where the layer will get rendered.
        :param layer_name: Name of the layer that we are interested in.
        :param alpha: The opacity of the layer to be rendered.
        :param tokens: Optional list of tokens to render. None means all tokens are rendered.
        """
        if layer_name not in self.map_api.non_geometric_polygon_layers:
            raise ValueError("{} is not a polygonal layer".format(layer_name))

        first_time = True
        records = getattr(self.map_api, layer_name)
        if tokens is not None:
            records = [r for r in records if r["token"] in tokens]
        if layer_name == "drivable_area":
            for record in records:
                polygons = [
                    self.map_api.extract_polygon(polygon_token)
                    for polygon_token in record["polygon_tokens"]
                ]

                for polygon in polygons:
                    if first_time:
                        label = layer_name
                        first_time = False
                    else:
                        label = None
                    ax.add_patch(
                        descartes.PolygonPatch(
                            polygon,
                            fc=self.color_map[layer_name],
                            alpha=alpha,
                            label=label,
                        )
                    )
        else:
            for record in records:
                polygon = self.map_api.extract_polygon(record["polygon_token"])

                if first_time:
                    label = layer_name
                    first_time = False
                else:
                    label = None

                ax.add_patch(
                    descartes.PolygonPatch(
                        polygon, fc=self.color_map[layer_name], alpha=alpha, label=label
                    )
                )

    def _render_line_layer(
        self, ax: Axes, layer_name: str, alpha: float, tokens: List[str] = None
    ) -> None:
        """
        Renders an individual non-geometric line layer on an axis.
        :param ax: The matplotlib axes where the layer will get rendered.
        :param layer_name: Name of the layer that we are interested in.
        :param alpha: The opacity of the layer to be rendered.
        :param tokens: Optional list of tokens to render. None means all tokens are rendered.
        """
        if layer_name not in self.map_api.non_geometric_line_layers:
            raise ValueError("{} is not a line layer".format(layer_name))

        first_time = True
        records = getattr(self.map_api, layer_name)
        if tokens is not None:
            records = [r for r in records if r["token"] in tokens]
        for record in records:
            if first_time:
                label = layer_name
                first_time = False
            else:
                label = None
            line = self.map_api.extract_line(record["line_token"])
            if line.is_empty:  # Skip lines without nodes
                continue
            xs, ys = line.xy

            if layer_name == "traffic_light":
                # Draws an arrow with the physical traffic light as the starting point, pointing to the direction on
                # where the traffic light points.
                ax.add_patch(
                    Arrow(
                        xs[0],
                        ys[0],
                        xs[1] - xs[0],
                        ys[1] - ys[0],
                        color=self.color_map[layer_name],
                        label=label,
                    )
                )
            else:
                ax.plot(
                    xs, ys, color=self.color_map[layer_name], alpha=alpha, label=label
                )

    def _get_layer_geom(
        self,
        patch_box: Tuple[float, float, float, float],
        patch_angle: float,
        layer_name: str,
    ) -> List[Geometry]:
        """
        Wrapper method that gets the geometries for each layer.
        :param patch_box: Patch box defined as [x_center, y_center, height, width].
        :param patch_angle: Patch orientation in degrees.
        :param layer_name: Name of map layer to be converted to binary map mask patch.
        :return: List of geometries for the given layer.
        """
        if layer_name in self.map_api.non_geometric_polygon_layers:
            return self._get_layer_polygon(patch_box, patch_angle, layer_name)
        elif layer_name in self.map_api.non_geometric_line_layers:
            return self._get_layer_line(patch_box, patch_angle, layer_name)
        else:
            raise ValueError("{} is not a valid layer".format(layer_name))

    def _layer_geom_to_mask(
        self,
        layer_name: str,
        layer_geom: List[Geometry],
        local_box: Tuple[float, float, float, float],
        canvas_size: Tuple[int, int],
    ) -> np.ndarray:
        """
        Wrapper method that gets the mask for each layer's geometries.
        :param layer_name: The name of the layer for which we get the masks.
        :param layer_geom: List of the geometries of the layer specified in layer_name.
        :param local_box: The local patch box defined as (x_center, y_center, height, width), where typically
            x_center = y_center = 0.
        :param canvas_size: Size of the output mask (h, w).
        """
        if layer_name in self.map_api.non_geometric_polygon_layers:
            return self._polygon_geom_to_mask(
                layer_geom, local_box, layer_name, canvas_size
            )
        elif layer_name in self.map_api.non_geometric_line_layers:
            return self._line_geom_to_mask(
                layer_geom, local_box, layer_name, canvas_size
            )
        else:
            raise ValueError("{} is not a valid layer".format(layer_name))

    @staticmethod
    def mask_for_polygons(polygons: MultiPolygon, mask: np.ndarray) -> np.ndarray:
        """
        Convert a polygon or multipolygon list to an image mask ndarray.
        :param polygons: List of Shapely polygons to be converted to numpy array.
        :param mask: Canvas where mask will be generated.
        :return: Numpy ndarray polygon mask.
        """
        if not polygons:
            return mask

        def int_coords(x):
            # function to round and convert to int
            return np.array(x).round().astype(np.int32)

        exteriors = [int_coords(poly.exterior.coords) for poly in polygons]
        interiors = [
            int_coords(pi.coords) for poly in polygons for pi in poly.interiors
        ]
        cv2.fillPoly(mask, exteriors, 1)
        cv2.fillPoly(mask, interiors, 0)

        return mask

    @staticmethod
    def mask_for_lines(lines: LineString, mask: np.ndarray) -> np.ndarray:
        """
        Convert a Shapely LineString back to an image mask ndarray.
        :param lines: List of shapely LineStrings to be converted to a numpy array.
        :param mask: Canvas where mask will be generated.
        :return: Numpy ndarray line mask.
        """
        if lines.geom_type == "MultiLineString":
            for line in lines:
                coords = np.asarray(list(line.coords), np.int32)
                coords = coords.reshape((-1, 2))
                cv2.polylines(mask, [coords], False, 1, 2)
        else:
            coords = np.asarray(list(lines.coords), np.int32)
            coords = coords.reshape((-1, 2))
            cv2.polylines(mask, [coords], False, 1, 2)

        return mask

    def _polygon_geom_to_mask(
        self,
        layer_geom: List[Polygon],
        local_box: Tuple[float, float, float, float],
        layer_name: str,
        canvas_size: Tuple[int, int],
    ) -> np.ndarray:
        """
        Convert polygon inside patch to binary mask and return the map patch.
        :param layer_geom: list of polygons for each map layer
        :param local_box: The local patch box defined as (x_center, y_center, height, width), where typically
            x_center = y_center = 0.
        :param layer_name: name of map layer to be converted to binary map mask patch.
        :param canvas_size: Size of the output mask (h, w).
        :return: Binary map mask patch with the size canvas_size.
        """
        if layer_name not in self.map_api.non_geometric_polygon_layers:
            raise ValueError("{} is not a polygonal layer".format(layer_name))

        patch_x, patch_y, patch_h, patch_w = local_box

        patch = self.get_patch_coord(local_box)

        canvas_h = canvas_size[0]
        canvas_w = canvas_size[1]

        scale_height = canvas_h / patch_h
        scale_width = canvas_w / patch_w

        trans_x = -patch_x + patch_w / 2.0
        trans_y = -patch_y + patch_h / 2.0

        map_mask = np.zeros(canvas_size, np.uint8)

        for polygon in layer_geom:
            new_polygon = polygon.intersection(patch)
            if not new_polygon.is_empty:
                new_polygon = affinity.affine_transform(
                    new_polygon, [1.0, 0.0, 0.0, 1.0, trans_x, trans_y]
                )
                new_polygon = affinity.scale(
                    new_polygon, xfact=scale_width, yfact=scale_height, origin=(0, 0)
                )

                if new_polygon.geom_type == "Polygon":
                    new_polygon = MultiPolygon([new_polygon])

                # if new_polygon.area < 1000:
                #     continue

                if not isinstance(new_polygon, MultiPolygon):
                    print(new_polygon)

                    continue

                map_mask = self.mask_for_polygons(new_polygon, map_mask)

        return map_mask

    def _line_geom_to_mask(
        self,
        layer_geom: List[LineString],
        local_box: Tuple[float, float, float, float],
        layer_name: str,
        canvas_size: Tuple[int, int],
    ) -> Optional[np.ndarray]:
        """
        Convert line inside patch to binary mask and return the map patch.
        :param layer_geom: list of LineStrings for each map layer
        :param local_box: The local patch box defined as (x_center, y_center, height, width), where typically
            x_center = y_center = 0.
        :param layer_name: name of map layer to be converted to binary map mask patch.
        :param canvas_size: Size of the output mask (h, w).
        :return: Binary map mask patch in a canvas size.
        """
        if layer_name not in self.map_api.non_geometric_line_layers:
            raise ValueError("{} is not a line layer".format(layer_name))

        patch_x, patch_y, patch_h, patch_w = local_box

        patch = self.get_patch_coord(local_box)

        canvas_h = canvas_size[0]
        canvas_w = canvas_size[1]
        scale_height = canvas_h / patch_h
        scale_width = canvas_w / patch_w

        trans_x = -patch_x + patch_w / 2.0
        trans_y = -patch_y + patch_h / 2.0

        map_mask = np.zeros(canvas_size, np.uint8)

        if layer_name == "traffic_light":
            return None

        for line in layer_geom:
            new_line = line.intersection(patch)
            if not new_line.is_empty:
                new_line = affinity.affine_transform(
                    new_line, [1.0, 0.0, 0.0, 1.0, trans_x, trans_y]
                )
                new_line = affinity.scale(
                    new_line, xfact=scale_width, yfact=scale_height, origin=(0, 0)
                )

                map_mask = self.mask_for_lines(new_line, map_mask)
        return map_mask

    def _get_layer_polygon(
        self,
        patch_box: Tuple[float, float, float, float],
        patch_angle: float,
        layer_name: str,
    ) -> List[Polygon]:
        """
        Retrieve the polygons of a particular layer within the specified patch.
        :param patch_box: Patch box defined as [x_center, y_center, height, width].
        :param patch_angle: Patch orientation in degrees.
        :param layer_name: name of map layer to be extracted.
        :return: List of Polygon in a patch box.
        """
        if layer_name not in self.map_api.non_geometric_polygon_layers:
            raise ValueError("{} is not a polygonal layer".format(layer_name))

        patch_x = patch_box[0]
        patch_y = patch_box[1]

        patch = self.get_patch_coord(patch_box, patch_angle)

        records = getattr(self.map_api, layer_name)

        polygon_list = []
        if layer_name == "drivable_area":
            for record in records:
                polygons = [
                    self.map_api.extract_polygon(polygon_token)
                    for polygon_token in record["polygon_tokens"]
                ]

                for polygon in polygons:
                    new_polygon = polygon.intersection(patch)
                    if not new_polygon.is_empty:
                        new_polygon = affinity.rotate(
                            new_polygon,
                            -patch_angle,
                            origin=(patch_x, patch_y),
                            use_radians=False,
                        )
                        new_polygon = affinity.affine_transform(
                            new_polygon, [1.0, 0.0, 0.0, 1.0, -patch_x, -patch_y]
                        )
                        if new_polygon.geom_type == "Polygon":
                            new_polygon = MultiPolygon([new_polygon])
                        polygon_list.append(new_polygon)
        else:
            for record in records:
                polygon = self.map_api.extract_polygon(record["polygon_token"])

                if polygon.is_valid:
                    new_polygon = polygon.intersection(patch)
                    if not new_polygon.is_empty:
                        new_polygon = affinity.rotate(
                            new_polygon,
                            -patch_angle,
                            origin=(patch_x, patch_y),
                            use_radians=False,
                        )
                        new_polygon = affinity.affine_transform(
                            new_polygon, [1.0, 0.0, 0.0, 1.0, -patch_x, -patch_y]
                        )
                        if new_polygon.geom_type == "Polygon":
                            new_polygon = MultiPolygon([new_polygon])
                        polygon_list.append(new_polygon)

        return polygon_list

    def _get_layer_line(
        self,
        patch_box: Tuple[float, float, float, float],
        patch_angle: float,
        layer_name: str,
    ) -> Optional[List[LineString]]:
        """
        Retrieve the lines of a particular layer within the specified patch.
        :param patch_box: Patch box defined as [x_center, y_center, height, width].
        :param patch_angle: Patch orientation in degrees.
        :param layer_name: name of map layer to be converted to binary map mask patch.
        :return: List of LineString in a patch box.
        """
        if layer_name not in self.map_api.non_geometric_line_layers:
            raise ValueError("{} is not a line layer".format(layer_name))

        if layer_name == "traffic_light":
            return None

        patch_x = patch_box[0]
        patch_y = patch_box[1]

        patch = self.get_patch_coord(patch_box, patch_angle)

        line_list = []
        records = getattr(self.map_api, layer_name)
        for record in records:
            line = self.map_api.extract_line(record["line_token"])
            if line.is_empty:  # Skip lines without nodes.
                continue

            new_line = line.intersection(patch)
            if not new_line.is_empty:
                new_line = affinity.rotate(
                    new_line, -patch_angle, origin=(patch_x, patch_y), use_radians=False
                )
                new_line = affinity.affine_transform(
                    new_line, [1.0, 0.0, 0.0, 1.0, -patch_x, -patch_y]
                )
                line_list.append(new_line)

        return line_list

    @staticmethod
    def get_patch_coord(
        patch_box: Tuple[float, float, float, float], patch_angle: float = 0.0
    ) -> Polygon:
        """
        Convert patch_box to shapely Polygon coordinates.
        :param patch_box: Patch box defined as [x_center, y_center, height, width].
        :param patch_angle: Patch orientation in degrees.
        :return: Box Polygon for patch_box.
        """
        patch_x, patch_y, patch_h, patch_w = patch_box

        x_min = patch_x - patch_w / 2.0
        y_min = patch_y - patch_h / 2.0
        x_max = patch_x + patch_w / 2.0
        y_max = patch_y + patch_h / 2.0

        patch = box(x_min, y_min, x_max, y_max)
        patch = affinity.rotate(
            patch, patch_angle, origin=(patch_x, patch_y), use_radians=False
        )

        return patch

    def _get_figsize(
        self, figsize: Union[None, float, Tuple[float, float]]
    ) -> Tuple[float, float]:
        """
        Utility function that scales the figure size by the map canvas size.
        If figsize is:
        - None      => Return default scale.
        - Scalar    => Scale canvas size.
        - Two-tuple => Use the specified figure size.
        :param figsize: The input figure size.
        :return: The output figure size.
        """
        # Divide canvas size by arbitrary scalar to get into cm range.
        canvas_size = np.array(self.map_api.canvas_edge)[::-1] / 200

        if figsize is None:
            return tuple(canvas_size)
        elif type(figsize) in [int, float]:
            return tuple(canvas_size * figsize)
        elif type(figsize) == tuple and len(figsize) == 2:
            return figsize
        else:
            raise Exception("Error: Invalid figsize: %s" % figsize)