-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathScenarioGUI.py
2251 lines (1838 loc) · 115 KB
/
ScenarioGUI.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os
import io
import sys
import json
import copy
import time
import pickle
import pkg_resources
import configparser
import numpy as np
from numpy import matlib
import zipfile
import tkinter as tk
import shapely.geometry
from tkinter import messagebox, filedialog, simpledialog
# matplotlib
import matplotlib.pyplot as plt
import matplotlib.patches as ptch
from matplotlib.widgets import Slider, Button, RadioButtons, CheckButtons
# Show plot in serif font (e.g. for publications)
# import matplotlib
# matplotlib.rcParams['mathtext.fontset'] = 'stix'
# matplotlib.rcParams['font.family'] = 'STIXGeneral'
# custom packages
import trajectory_planning_helpers as tph
import scenario_testing_tools
# custom modules
import helper_funcs
"""
Python version: 3.7
Created by: Tim Stahl
Created on: 17.04.2019
Graphic user interface allowing to generate, load and export a scenario with one or multiple vehicles in a scene.
The bounds, as well as the path and velocity profile of a vehicle are all drawn and manipulated by using the pointing
device only.
"""
# path pointing to config-file
CONFIG_FILE = os.path.dirname(os.path.realpath(__file__)) + '/params/config.ini'
def check_py_dep() -> None:
"""
Checks if all dependencies listed in the 'requirements.txt' are installed.
"""
# get current path
module_path = os.path.dirname(os.path.abspath(__file__))
# read dependencies from requirements.txt
requirements_path = os.path.join(module_path, 'requirements.txt')
dependencies = []
with open(requirements_path, 'r') as fh:
line = fh.readline()
while line:
dependencies.append(line.rstrip())
line = fh.readline()
# check dependencies
pkg_resources.require(dependencies)
class ScenarioArchitect:
"""
Main class for the GUI.
"""
def __init__(self,
load_file: str = None,
data_mode: bool = False) -> None:
"""
Initializes the Scenario Architect. All internal variables and scenario entities are created. The graphical
interface (e.g. buttons and switches) as well as plot-areas are initialized.
:param load_file: (optional) existing scenario file to be loaded on startup.
:param data_mode: (optional) if set to "True", no GUI will be displayed --> used for script interfacing
:return
"""
# get config-file
self.__config = configparser.ConfigParser()
if not self.__config.read(CONFIG_FILE):
raise ValueError('Specified config-file does not exist or is empty!')
self.__color_dict = json.loads(self.__config.get('VISUAL', 'color_dict'))
self.__keep_veh_plot = self.__config.getboolean('VISUAL', 'keep_veh_plot')
self.__import_track_shift = self.__config.getboolean('TRACK_IMPORT', 'shift_track')
# import ggv from file
top_path = os.path.dirname(os.path.abspath(__file__))
ggv_path = top_path + "/params/veh_dyn_info/ggv.csv"
ax_max_machines_path = top_path + "/params/veh_dyn_info/ax_max_machines.csv"
self.__ggv, self.__ax_max_machines = tph.import_veh_dyn_info. \
import_veh_dyn_info(ggv_import_path=ggv_path,
ax_max_machines_import_path=ax_max_machines_path)
# --------------------------------------------------------------------------------------------------------------
# - INIT PLOTS -------------------------------------------------------------------------------------------------
# --------------------------------------------------------------------------------------------------------------
# -- main plot -------------------------------------------------------------------------------------------------
self.__fig_main, ax = plt.subplots(figsize=(10, 6))
self.__fig_main.canvas.set_window_title("Scenario GUI")
self.__plot_all_vehicles = False
self.__plot_all_vehicles_text = False
# init data rows
self.__x_marks, = plt.plot([], [], 'xk', zorder=98)
self.__x_mark_highlight, = plt.plot([], [], 'ok', zorder=97, alpha=0.5)
self.__bound_connectors, = plt.plot([], [], '--', color=self.__color_dict['TUM_grey_dark'], zorder=5)
self.__track_ptch_hdl = None
self.__text_hdl = {}
# set plot layout
plt.axis([0, self.__config.getfloat('VISUAL', 'default_x_scale'),
0, self.__config.getfloat('VISUAL', 'default_x_scale') * 0.8])
plt.tight_layout(rect=(0.05, 0.03, 0.8, 1.0))
self.__axes_plane = self.__fig_main.gca()
self.__axes_plane.grid()
self.__axes_plane.set_aspect('equal', 'box')
self.__axes_plane.set_xlabel('x in m')
self.__axes_plane.set_ylabel('y in m')
# register mouse events
self.__fig_main.canvas.mpl_connect('button_press_event', self.onclick_main)
self.__fig_main.canvas.mpl_connect('motion_notify_event', self.onmove_main)
self.__fig_main.canvas.mpl_connect('button_release_event', self.onrelease_main)
# change axis of __axes_plane (should be on the left)
pos_fig_plane = self.__axes_plane.get_position()
points_fig_plane = pos_fig_plane.get_points()
points_fig_plane[1][0] -= 0.05
points_fig_plane[1][1] += 0.05
pos_fig_plane.set_points(points_fig_plane)
self.__axes_plane.set_position(pos_fig_plane)
# -- velocity plot ---------------------------------------------------------------------------------------------
self.__fig_time, axes = plt.subplots(4, 1, figsize=(8, 9)) # create a window (8x9) with 4 plots
self.__fig_time.canvas.set_window_title("Temporal Plot")
self.__axes_a_t = axes[0]
self.__axes_a_t.grid()
self.__axes_a_t.set_ylabel("a in m/s²")
self.__axes_a_t.xaxis.set_ticks_position('none') # x-ticks invisible
plt.setp(self.__axes_a_t.get_xticklabels(), visible=False) # set x-ticks invisible
# self.__axes_a_t.set_xlim(left=0.0) # force 0.0 to be lower bound of x-axis
# NOTE: fixing lower bound of x-axis here brakes auto-scaling --> enforced on every plot update
self.__axes_v_t = axes[1]
plt.subplot(412, sharex=self.__axes_a_t) # 4 lines, 1 row, number 2 of the plots
self.__axes_v_t = plt.gca()
self.__axes_v_t.grid()
self.__axes_v_t.set_xlabel("t in s", labelpad=0)
self.__axes_v_t.set_ylabel("v in m/s")
self.__axes_v_t.xaxis.set_ticks_position('none') # x-ticks invisible
self.__axes_v_t.tick_params(axis='x', which='major', pad=0) # x-tick labels closer to axis
# self.__axes_v_t.set_ylim(bottom=0.0) # force 0.0 to be lower bound of y-axis
self.__axes_v_s = axes[2]
self.__axes_v_s.grid()
self.__axes_v_s.set_xlabel("s in m", labelpad=0)
self.__axes_v_s.set_ylabel("v in m/s")
self.__axes_v_s.xaxis.set_ticks_position('none') # x-ticks invisible
self.__axes_v_s.tick_params(axis='x', which='major', pad=0) # x-tick labels closer to axis
# self.__axes_v_s.set_ylim(bottom=0.0) # force 0.0 to be lower bound of y-axis
# self.__axes_v_s.set_xlim(left=0.0) # force 0.0 to be lower bound of x-axis
self.__axes_ssm = axes[3]
plt.subplot(414, sharex=self.__axes_a_t) # 4 lines, 1 row, number 4 of the plots
self.__axes_ssm = plt.gca() # shows the plot if the axe is shared
self.__axes_ssm.grid()
self.__axes_ssm.set_xlabel("t in s", labelpad=0)
self.__axes_ssm.set_ylabel("TTC in s | DSS/10 in m")
self.__axes_ssm.xaxis.set_ticks_position('none') # x-ticks invisible
self.__axes_ssm.tick_params(axis='x', which='major', pad=0) # x-tick labels closer to axis
self.__axes_ssm.set_ylim(bottom=-5.0, top=15.0)
# instantiate a second axes that shares the same x-axis
self.__axes_ssm2 = self.__axes_ssm.twinx()
self.__axes_ssm.set_zorder(self.__axes_ssm.get_zorder() + 1) # set parent axis zorder higher for event handler
self.__axes_ssm2.set_ylim(bottom=-5.0, top=15.0)
self.__axes_ssm2.set_yticks([7.5, 12.5])
self.__axes_ssm2.set_yticklabels(["Static\nsafety", "Dynamic\nsafety"])
# -- change axis location of __axes_v_t and __axes_ssm--
pos_acc_ax = self.__axes_a_t.get_position()
pos_vel_ax = self.__axes_v_t.get_position()
pos_sp_ttc = self.__axes_ssm.get_position()
# get limits of plot boxes (in percent of the plot window) [[left, low], [right, up]]
points_acc_ax = pos_acc_ax.get_points()
points_vel_ax = pos_vel_ax.get_points()
points_sp_ttc = pos_sp_ttc.get_points()
# set new frame of the velocity plot
points_vel_ax[0][1] += points_acc_ax[0][1] - 0.01 - points_vel_ax[1][1] # move up to reveal description
points_vel_ax[1][1] = points_acc_ax[0][1] - 0.01 # move closer to bottom of acceleration plot (1% offset)
pos_vel_ax.set_points(points_vel_ax)
# changes the position of the TTC-x plot (should be lower)
points_sp_ttc[0][1] -= 0.02
points_sp_ttc[1][1] -= 0.02
pos_sp_ttc.set_points(points_sp_ttc)
# update the new plot setups
self.__axes_v_t.set_position(pos_vel_ax)
self.__axes_ssm.set_position(pos_sp_ttc)
# Member variables for manipulation of the velocity profile
self.__vel_manip_handle = None
self.__vel_manip_handle_tmp = None
self.__vel_mod_range = None
self.__vel_mod_y = None
self.__vel_mod_protect = {}
# event handles for velocity plot (moving mouse or pressing mouse buttons)
self.__fig_time.canvas.mpl_connect('button_press_event', self.onclick_vel)
self.__fig_time.canvas.mpl_connect('button_release_event', self.onrelease_vel)
self.__fig_time.canvas.mpl_connect('motion_notify_event', self.onmove_vel)
# add patch for limits (red shade for velocity bounds not to be crossed)
np.sqrt(max(self.__ggv[:, 1]) ** 2 + max(self.__ggv[:, 2]) ** 2)
max_comb_acc = np.max(self.__ggv[:, 1:]) * self.__config.getfloat('SAFETY', 'comb_acc_factor')
patch_xy = np.array([[-1000, -1000, 1000, 1000], [max_comb_acc, 1000, 1000, max_comb_acc]]).T
track_ptch = ptch.Polygon(patch_xy, facecolor="red", alpha=0.3, zorder=1)
self.__axes_a_t.add_artist(track_ptch)
patch_xy = np.array([[-1000, -1000, 1000, 1000], [-max_comb_acc, -1000, -1000, -max_comb_acc]]).T
track_ptch = ptch.Polygon(patch_xy, facecolor="red", alpha=0.3, zorder=1)
self.__axes_a_t.add_artist(track_ptch)
# add patch limits for SSM plot
if self.__config.get('SAFETY', 'ssm_safety') == 'ttc':
min_ssm = self.__config.getfloat('SAFETY', 'ttc_crit')
mid_ssm = self.__config.getfloat('SAFETY', 'ttc_undefined')
elif self.__config.get('SAFETY', 'ssm_safety') == 'dss':
min_ssm = self.__config.getfloat('SAFETY', 'dss_crit') / 10.0
mid_ssm = self.__config.getfloat('SAFETY', 'dss_undefined') / 10.0
else:
min_ssm = 0.0
mid_ssm = 0.0
patch_xy = np.array([[-1000, -1000, 1000, 1000], [min_ssm, -1000, -1000, min_ssm]]).T
limit_ptch = ptch.Polygon(patch_xy, facecolor="red", alpha=0.3, zorder=1)
self.__axes_ssm.add_artist(limit_ptch)
patch_xy = np.array([[-1000, -1000, 1000, 1000], [mid_ssm, min_ssm, min_ssm, mid_ssm]]).T
limit_ptch = ptch.Polygon(patch_xy, facecolor="orange", alpha=0.3, zorder=1)
self.__axes_ssm.add_artist(limit_ptch)
# define cursor highlighting selected position in the temporal plot (red vertical line)
self.__vel_ax_cursor, = self.__axes_v_t.plot([0.0], [0.0], lw=1, color='r', zorder=999)
self.__acc_ax_cursor, = self.__axes_a_t.plot([0.0], [0.0], lw=1, color='r', zorder=999)
self.__ttc_ax_cursor, = self.__axes_ssm.plot([0.0], [0.0], lw=1, color='r', zorder=999)
self.__cursor_last_t = 0.0
# handles for automatic safety rating in scenario
self.__safety_dyn_safe, = self.__axes_ssm.plot([], [], lw=10, color=self.__color_dict["TUM_green"], alpha=0.5,
zorder=999, label=" Safe ")
self.__safety_dyn_unsafe, = self.__axes_ssm.plot([], [], lw=10, color=self.__color_dict["TUM_orange"],
alpha=0.5, zorder=999, label=" Unsafe")
self.__safety_stat_safe, = self.__axes_ssm.plot([], [], lw=10, color=self.__color_dict["TUM_green"], alpha=0.5,
zorder=999)
self.__safety_stat_unsafe, = self.__axes_ssm.plot([], [], lw=10, color=self.__color_dict["TUM_orange"],
alpha=0.5, zorder=999)
# store file-path (if saving again, suggest same name)
self.__load_file = load_file
# --------------------------------------------------------------------------------------------------------------
# - DEFINE GUI ELEMENTS (BUTTONS, SLIDERS, ...) ----------------------------------------------------------------
# --------------------------------------------------------------------------------------------------------------
# Set time window as active figure
plt.figure(self.__fig_time.number)
# Playback button
plybck_ax = self.__fig_time.add_axes([0.02, 0.95, 0.15, 0.04])
button_plybck = Button(plybck_ax, 'Playback', color=self.__config.get('VISUAL', 'btn_color'),
hovercolor='0.975')
button_plybck.on_clicked(self.on_playback_click)
# Open window with SSM info
ssm = self.__fig_time.add_axes([0.22, 0.95, 0.15, 0.04])
button_ssm = Button(ssm, 'SSM Information', color=self.__config.get('VISUAL', 'btn_color'),
hovercolor='0.975')
button_ssm.on_clicked(self.on_ssm_click)
# Set main window as active figure
plt.figure(self.__fig_main.number)
# Text
text_ax = self.__fig_main.add_axes([0.8, 0.82, 0.15, 0.2])
text_ax.axis('off')
text_ax.set_navigate(False)
self.__entity_descr = text_ax.text(0.0, 0.0, "Select entity\nto be drawn:")
# Radio buttons for entity selection
rax = self.__fig_main.add_axes([0.8, 0.55, 0.15, 0.25], facecolor=self.__config.get('VISUAL', 'btn_color'))
self.__radio = RadioButtons(rax, ('None', 'bound_l', 'bound_r', 'veh_1', 'veh_2', 'veh_3', 'veh_4', 'veh_5'),
active=0)
self.__radio.on_clicked(self.toggled_radio)
# Reset all button
button_reset = Button(self.__fig_main.add_axes([0.8, 0.50, 0.15, 0.04]), 'Reset all Entities',
color=self.__config.get('VISUAL', 'btn_color'),
hovercolor='0.975')
button_reset.on_clicked(self.reset_all)
# Reset button
button_reset_ent = Button(self.__fig_main.add_axes([0.8, 0.45, 0.15, 0.04]), 'Reset Entity',
color=self.__config.get('VISUAL', 'btn_color'),
hovercolor='0.975')
button_reset_ent.on_clicked(self.reset_ent)
# Specify import button
button_import = Button(self.__fig_main.add_axes([0.8, 0.40, 0.15, 0.04]), 'Import Scen.',
color=self.__config.get('VISUAL', 'btn_color'),
hovercolor='0.975')
button_import.on_clicked(self.load_pckl)
# Specify export button
button_export = Button(self.__fig_main.add_axes([0.8, 0.35, 0.15, 0.04]), 'Export Scen.',
color=self.__config.get('VISUAL', 'btn_color'),
hovercolor='0.975')
button_export.on_clicked(self.export_to_file)
# Specify import track button
button_import_track = Button(self.__fig_main.add_axes([0.8, 0.30, 0.15, 0.04]), 'Import Track',
color=self.__config.get('VISUAL', 'btn_color'),
hovercolor='0.975')
button_import_track.on_clicked(self.load_track)
# Plot all vehicles checkbox
check_all_veh = CheckButtons(self.__fig_main.add_axes([0.8, 0.19, 0.15, 0.1]), ['All Poses', 'Add Text'],
[self.__plot_all_vehicles, self.__plot_all_vehicles_text])
check_all_veh.on_clicked(self.toggled_veh)
# Open plot window button
button_plt_wndw = Button(self.__fig_main.add_axes([0.8, 0.09, 0.15, 0.04]), 'Open Plot',
color=self.__config.get('VISUAL', 'btn_color'),
hovercolor='0.975')
button_plt_wndw.on_clicked(self.open_plot_window)
# Scaling reset button
button = Button(self.__fig_main.add_axes([0.8, 0.02, 0.15, 0.04]), 'Reset Scale',
color=self.__config.get('VISUAL', 'btn_color'),
hovercolor='0.975')
button.on_clicked(self.reset)
# Scaling slider
self.__sld_x_axis = Slider(self.__fig_main.add_axes([0.1, 0.02, 0.6, 0.03],
facecolor=self.__config.get('VISUAL', 'btn_color')),
label='Scale',
valmin=self.__config.getfloat('VISUAL', 'delta_xy'),
valmax=self.__config.getfloat('VISUAL', 'max_x_scale'),
valinit=self.__config.getfloat('VISUAL', 'default_x_scale'),
valstep=self.__config.getfloat('VISUAL', 'delta_xy'))
self.__sld_x_axis_cid = self.__sld_x_axis.on_changed(self.change_ratio)
# --------------------------------------------------------------------------------------------------------------
# - INIT VARIABLES AND ENTITIES --------------------------------------------------------------------------------
# --------------------------------------------------------------------------------------------------------------
# entity container (holding instances of all entities in the scenario) - initialize with two bound entities
self.__ent_cont = [helper_funcs.src.ScenarioEntities.Bound(id_in='bound_l', plane_axis=self.__axes_plane),
helper_funcs.src.ScenarioEntities.Bound(id_in='bound_r', plane_axis=self.__axes_plane)]
# add ego-vehicle
self.__ent_cont.append(
helper_funcs.src.ScenarioEntities.Vehicle(i_in=1,
plane_axis=self.__axes_plane,
a_t_axis=self.__axes_a_t,
v_t_axis=self.__axes_v_t,
v_s_axis=self.__axes_v_s, type_ego=True,
ssm_t_axis=self.__axes_ssm,
color_str=self.get_veh_color(1),
veh_width=self.__config.getfloat('VEHICLE', 'veh_width'),
veh_length=self.__config.getfloat('VEHICLE', 'veh_length'),
plan_hor=self.__config.getfloat('FILE_EXPORT',
'export_time_traj_horizon')),
)
# add 4 other vehicles
for i in range(2, 6):
self.__ent_cont.append(
helper_funcs.src.ScenarioEntities.Vehicle(i_in=i,
plane_axis=self.__axes_plane,
a_t_axis=self.__axes_a_t,
v_t_axis=self.__axes_v_t,
v_s_axis=self.__axes_v_s,
ssm_t_axis=self.__axes_ssm,
color_str=self.get_veh_color(i),
veh_width=self.__config.getfloat('VEHICLE', 'veh_width'),
veh_length=self.__config.getfloat('VEHICLE', 'veh_length'))
)
# currently selected entity (via radio-buttons - one element in the list of '__ent_cont')
self.__sel_ent = None
self.__pidx_vel = None
self.__pidx_main = None
# load scenario, if provided
if load_file is not None:
self.load_pckl(_=None,
file_path=load_file)
if not data_mode:
plt.show()
def __del__(self):
plt.close(self.__fig_main)
plt.close(self.__fig_time)
# ------------------------------------------------------------------------------------------------------------------
# - INTERACTION WITH GUI ELEMENTS ----------------------------------------------------------------------------------
# ------------------------------------------------------------------------------------------------------------------
def toggled_radio(self,
_: str = None) -> None:
"""
Called whenever the radio button selection changes.
:param _: selected value (string of description), not used since accessable via radio.value_selected
:return
"""
# load latest stored information in temporary (live-visualized container)
for obj in self.__ent_cont:
obj.data_coord_tmp = copy.deepcopy(obj.data_coord)
# find selected entity in container
self.__sel_ent = None
for obj in self.__ent_cont:
if obj.id == self.__radio.value_selected:
self.__sel_ent = obj
break
self.update_plot()
def toggled_veh(self,
text_label) -> None:
"""
Called whenever the checkbox 'All Poses' was clicked.
:param text_label: clicked text-label besides checkbox (used to discriminate checked boxes).
:return
"""
if text_label == 'All Poses':
self.__plot_all_vehicles = not self.__plot_all_vehicles
else:
self.__plot_all_vehicles_text = not self.__plot_all_vehicles_text
self.update_plot()
def change_ratio(self,
_) -> None:
"""
Called when scaling slider was moved. Manipulate plot scaling accordingly.
"""
self.__axes_plane.set_ylim(0.0, self.__sld_x_axis.val * 0.8)
self.__axes_plane.set_xlim(0.0, self.__sld_x_axis.val)
self.__fig_main.canvas.draw_idle()
def reset(self,
_):
"""
Called when the scaling's reset-button was clicked.
"""
self.__sld_x_axis.reset()
def reset_ent(self,
_) -> None:
"""
Called when 'Reset Entity'-button was clicked. Resets the corresponding entity.
"""
# reset container
if self.__radio.value_selected != 'None':
# remove entity from list of protected velocity profiles
self.__vel_mod_protect.pop(self.__radio.value_selected, None)
for obj in self.__ent_cont:
if obj.id == self.__radio.value_selected:
obj.data_coord = None
obj.data_exp = None
obj.data_vel_coord = None
# remove vehicle visualization
if obj.TYPE_VEHICLE:
obj.highlight_pose(t_in=None)
# update temporary data
obj.data_coord_tmp = copy.deepcopy(obj.data_coord)
# update plot
self.update_plot()
def reset_all(self,
_) -> None:
# reset container
if self.__radio.value_selected != 'None':
# remove entity from list of protected velocity profiles
self.__vel_mod_protect.pop(self.__radio.value_selected, None)
for obj in self.__ent_cont:
obj.data_coord = None
obj.data_exp = None
obj.data_vel_coord = None
# remove vehicle visualization
if obj.TYPE_VEHICLE:
obj.highlight_pose(t_in=None)
# update temporary data
obj.data_coord_tmp = copy.deepcopy(obj.data_coord)
# update plot
self.update_plot()
def on_playback_click(self,
_) -> None:
"""
Called when the 'payback'-button is clicked.
"""
# playback the scenario in real time (with updates as fast as possible)
# stop edit mode in main axis
if self.__radio.value_selected != 'None' and self.__sel_ent.data_coord_tmp is not None and \
self.__sel_ent.data_coord_tmp.shape > self.__sel_ent.data_coord.shape:
self.__sel_ent.data_coord_tmp = self.__sel_ent.data_coord
self.update_plot(hover_mode=True)
# get range of x axis
t_range = self.__axes_a_t.get_xlim()
t = t_range[0]
# store axis limits in order to avoid readout every iteration
vel_ylim = self.__axes_v_t.get_ylim()
acc_ylim = self.__axes_a_t.get_ylim()
ttc_ylim = self.__axes_ssm.get_ylim()
while t < t_range[1]:
tic = time.time()
# update cursor in velocity window
self.__vel_ax_cursor.set_data([t, t], vel_ylim)
self.__acc_ax_cursor.set_data([t, t], acc_ylim)
self.__ttc_ax_cursor.set_data([t, t], ttc_ylim)
self.__fig_time.canvas.draw_idle()
# for all trajectories holding temporal information, calculate index
for obj in self.__ent_cont:
if obj.TYPE_VEHICLE:
obj.highlight_pose(t_in=t)
plt.pause(0.001)
t += time.time() - tic
def on_ssm_click(self,
_) -> None:
"""
Called when the 'SSM information'-button is clicked.
"""
# definition of a function to destroy and refresh / reload the window
def button_ok_click():
window.destroy()
# definition of a function, which opens a new window with information about the SSM calculation
def button_information_calculation():
messagebox.showinfo('SSM Information',
'Key facts for the calculation of the SSM:\n'
'- The lane-based coordinates can only be calculated for paths after the first point '
'and before the last point of the lane-based coordinate system.\n'
'- Both bounds must be specified for the calculation of the SSMs.\n'
'- The SSM scores are only calculated for the ego vehicle in relation to each other '
'vehicle.')
def calculate_info():
# init variables
# Variable that stores whether an ego vehicle is present or not (False = no ego vehicle)
ego_veh_used = False
# variables to calculate the lateral distance between teh vehicles
pos_ego_stamps = None
# counter for bounds
counter_bound = 0
veh_width = self.__config.getfloat('VEHICLE', 'veh_width')
veh_length = self.__config.getfloat('VEHICLE', 'veh_length')
for bound in self.__ent_cont:
if bound.TYPE_BOUND and bound.get_mode_coord() is not None:
counter_bound += 1
# generate information about the SSMs
for obj in self.__ent_cont:
if obj.TYPE_VEHICLE:
info_txt = ""
# SSM information for veh_1 (ego-vehicle)
if obj.id == 'veh_1':
# if the ego-vehicle is used
if obj.get_mode_coord() is not None and counter_bound == 2:
info_txt = 'There is no SSM calculation for the ego-vehicle.'
ego_veh_used = True
pos_ego_stamps = obj.data_ssm[:, 3:5]
# if the Ego-Vehicle is not specified
elif obj.get_mode_coord() is None and counter_bound == 2:
info_txt = 'Ego-vehicle is not specified yet!'
else:
info_txt = 'SSM calculation is not possible since one or both bounds are not specified.'
# SSM information for the other vehicles
else:
# check if preconditions hold
if obj.get_mode_coord() is not None and max(obj.data_ssm[:, 1]) != 0 and ego_veh_used is True \
and counter_bound == 2 and obj.data_ssm is not None:
# check if vehicles drive in same direction
driving_same_direction = ((pos_ego_stamps[0, 0] < pos_ego_stamps[-1, 0]
and obj.data_ssm[0, 3] < obj.data_ssm[-1, 3])
or (pos_ego_stamps[0, 0] > pos_ego_stamps[-1, 0]
and obj.data_ssm[0, 3] > obj.data_ssm[-1, 3]))
if driving_same_direction:
# get minimal values
i_ttc = np.nanargmin(obj.data_ssm[:, 1])
i_dss = np.nanargmin(obj.data_ssm[:, 2])
print(obj.data_ssm[:, 2])
# check for collision at given points
if not (abs(pos_ego_stamps[i_ttc, 0] - obj.data_ssm[i_ttc, 3]) < veh_length * 1.2
and abs(pos_ego_stamps[i_ttc, 1] - obj.data_ssm[i_ttc, 4]) < veh_width * 1.2):
ttc_col_pre = 'no '
else:
ttc_col_pre = 'possible '
if not (abs(pos_ego_stamps[i_dss, 0] - obj.data_ssm[i_dss, 3]) < veh_length * 1.2
and abs(pos_ego_stamps[i_dss, 1] - obj.data_ssm[i_dss, 4]) < veh_width * 1.2):
dss_col_pre = 'no '
else:
dss_col_pre = 'possible '
# generate info text
info_txt = ('The minimal TTC is ' + format(obj.data_ssm[i_ttc, 1], '.2f')
+ ' s at t=' + format(obj.data_ssm[i_ttc, 0], '.2f') + ' s. '
+ '(' + ttc_col_pre + 'collision)\n'
+ 'The minimal DSS is ' + format(obj.data_ssm[i_dss, 2], '.2f')
+ ' m at t=' + format(obj.data_ssm[i_dss, 0], '.2f') + ' s. '
+ '(' + dss_col_pre + 'collision)')
else:
info_txt = 'Vehicle is driving in opposing direction!'
# if not all bounds specified
elif counter_bound < 2:
print("updated")
info_txt = 'SSM calculation is not possible since one or both bounds are not specified.'
# if the ego-vehicle is not used
elif ego_veh_used is False and counter_bound == 2:
info_txt = 'SSM calculation is not possible since the ego-vehicle (veh_1) is not specified!'
# if the vehicle is not specified
elif obj.get_mode_coord() is None and obj.data_ssm is None:
info_txt = 'Vehicle "' + str(obj.id) + '" is not specified!'
# set label text
label_info_dict[obj.id].configure(text=info_txt)
# -- init window elements (labels and buttons) --
# open window
window = tk.Tk()
window.title('TTC information')
window.geometry('600x300')
# text at the top of the new window
label = tk.Label(window, text='This window provides detailed information about the SMMs:')
label.place(x=10, y=5)
# init vehicle labels
y = 50
label_info_dict = dict()
for obj_ in self.__ent_cont:
if obj_.TYPE_VEHICLE:
label_descr = tk.Label(window, text=obj_.id + ":")
label_descr.place(x=10, y=y)
label_info_dict[obj_.id] = tk.Label(window, text='--', anchor="e", justify=tk.LEFT)
label_info_dict[obj_.id].place(x=100, y=y)
y += 40
# update data
calculate_info()
# button to refresh the window
button = tk.Button(master=window, text='Refresh', command=calculate_info)
button.place(x=10, y=275, width=150, height=20)
# button to close the window
button_ok = tk.Button(master=window, text='Close', command=button_ok_click)
button_ok.place(x=210, y=275, width=150, height=20)
# button to open a window with information about the ttc calculation the window
button_info = tk.Button(master=window, text='SSM calculation info', command=button_information_calculation)
button_info.place(x=410, y=275, width=150, height=20)
tk.mainloop()
def open_plot_window(self,
_) -> None:
"""
Called when the 'Open Plot'-button is clicked.
"""
# dump the whole plot in a pickle
inx = list(self.__fig_main.axes).index(self.__axes_plane)
buf = io.BytesIO()
pickle.dump(self.__fig_main, buf)
buf.seek(0)
# load pickle in new plot figure (without buttons)
fig_plot = pickle.load(buf)
fig_plot.set_tight_layout(True)
# delete everything except main axes
for i, ax in enumerate(fig_plot.axes):
if i != inx:
fig_plot.delaxes(ax)
fig_plot.show()
# ------------------------------------------------------------------------------------------------------------------
# - PATH AND VELOCITY CALCULATIONS (AND ACCORDING PLOT UPDATES) ----------------------------------------------------
# ------------------------------------------------------------------------------------------------------------------
def update_plot(self,
hover_mode=False,
force_update=False) -> None:
"""
Update both - path and velocity plot (including relevant calculations).
:param hover_mode: if set to 'True' temporary values (e.g. currently manipulated trajectory without fixed
last coordinate will be live-visualized).
:param force_update: if set to 'True' all plots will be forced to show updates (not only obvious changes).
:return
"""
if not hover_mode:
for obj in self.__ent_cont:
obj.tmp_mode = False
else:
for obj in self.__ent_cont:
obj.tmp_mode = True
self.update_path_plot()
self.update_vel_plot(force_update=force_update)
for obj in self.__ent_cont:
obj.tmp_mode = False
def update_path_plot(self) -> None:
"""
Update information relevant for the path plot (bound- and path-handling) and trigger plot updates.
"""
x_marks = [[], []]
for obj in self.__ent_cont:
if obj.get_mode_coord() is not None and obj.get_mode_coord().size > 2:
# -- calculate new information -------------------------------------------------------------------------
if self.__radio.value_selected == obj.id:
# xmarks for active entry
x_marks[0].extend(obj.get_mode_coord()[:, 0])
x_marks[1].extend(obj.get_mode_coord()[:, 1])
if obj.TYPE_VEHICLE:
# calculate heading
tangvecs = np.stack((obj.get_mode_coord()[1:, 0] - obj.get_mode_coord()[:-1, 0],
obj.get_mode_coord()[1:, 1] - obj.get_mode_coord()[:-1, 1]), axis=1)
psi_vel = np.arctan2(tangvecs[:, 1], tangvecs[:, 0]) - np.pi / 2
psi_vel[psi_vel < -np.pi] += 2 * np.pi
# calculate spline
x_coeff, y_coeff, _, _ = tph.calc_splines.calc_splines(path=obj.get_mode_coord(),
psi_s=psi_vel[0],
psi_e=psi_vel[-1])
dpoints, spln_inds, t_val, dists_int = tph.interp_splines.interp_splines(coeffs_x=x_coeff,
coeffs_y=y_coeff,
stepsize_approx=2.0,
incl_last_point=True)
psi, kappa = tph.calc_head_curv_an.calc_head_curv_an(coeffs_x=x_coeff,
coeffs_y=y_coeff,
ind_spls=spln_inds,
t_spls=t_val)
s = np.concatenate(([0], np.cumsum(np.sqrt(np.sum(np.power(np.diff(dpoints, axis=0), 2), axis=1)))))
# export s, x, y, psi, kappa, vx, ax (if data available and changed)
if (obj.data_vel_coord is None
or (self.__pidx_main is not None and obj == self.__radio.value_selected)
or not np.array_equal(obj.get_mode_coord(), obj.data_vel_coord)):
obj.data_exp = np.zeros((psi.shape[0], 7))
obj.data_exp[:, 0:5] = np.column_stack((s, dpoints, psi, kappa))
# -- update plots --------------------------------------------------------------------------------------
obj.update_xy_plot()
else:
obj.update_xy_plot(reset=True)
self.__x_marks.set_data(x_marks)
# plot track
if self.__track_ptch_hdl is not None:
self.__track_ptch_hdl.remove()
self.__track_ptch_hdl = None
# expect bounds on first two entities
if self.__ent_cont[0].TYPE_BOUND and self.__ent_cont[1].TYPE_BOUND:
if self.__ent_cont[0].get_mode_coord() is not None and self.__ent_cont[1].get_mode_coord() is not None:
# track patch
patch_xy = np.vstack((self.__ent_cont[0].get_mode_coord(),
np.flipud(self.__ent_cont[1].get_mode_coord())))
track_ptch = ptch.Polygon(patch_xy, facecolor="black", alpha=0.2, zorder=1)
self.__track_ptch_hdl = self.__axes_plane.add_artist(track_ptch)
# connecting lines
n_shared_el = int(min(self.__ent_cont[0].get_mode_coord().size / 2,
self.__ent_cont[1].get_mode_coord().size / 2))
data_bound_lines = [[], []]
if n_shared_el > 1:
for i in range(n_shared_el):
data_bound_lines[0].extend([self.__ent_cont[0].get_mode_coord()[i, 0],
self.__ent_cont[1].get_mode_coord()[i, 0], None])
data_bound_lines[1].extend([self.__ent_cont[0].get_mode_coord()[i, 1],
self.__ent_cont[1].get_mode_coord()[i, 1], None])
self.__bound_connectors.set_data(data_bound_lines)
else:
self.__bound_connectors.set_data([[], []])
else:
raise ValueError("Something went wrong! Assumed bound data on first two container entries!")
self.__fig_main.canvas.draw_idle()
def update_vel_plot(self,
force_update=False) -> None:
"""
Update information relevant for the path plot (bound- and path-handling) and trigger plot updates.
:param force_update: (optional) if set to 'True', all entities are forced to be updated
if set to 'False', only obviously changed entities are updated
:return
"""
# plot track
if self.__vel_manip_handle is not None:
self.__vel_manip_handle.remove()
self.__vel_manip_handle = None
# check if any of the text next to the vehicle poses is initially plotted (then all need an update due to
# repositioning)
all_veh_text_need_update = False
if self.__plot_all_vehicles and self.__plot_all_vehicles_text and 'veh' not in self.__radio.value_selected:
for obj in self.__ent_cont:
if obj.TYPE_VEHICLE and obj.get_mode_coord() is not None and obj.data_exp is not None \
and not obj.id + "_all" in self.__text_hdl:
all_veh_text_need_update = True
break
# -------------------------------------- calculate center line -------------------------------------------------
calc_center_line = None
# get the center line and the distance s
if self.__ent_cont[0].TYPE_BOUND and self.__ent_cont[1].TYPE_BOUND:
if self.__ent_cont[0].get_mode_coord() is not None and \
self.__ent_cont[1].get_mode_coord() is not None:
# calculate number of shared elements of the left and right bound
n_shared_el = min(self.__ent_cont[0].get_mode_coord().shape[0],
self.__ent_cont[1].get_mode_coord().shape[0])
# for the number of not shared elements
not_shared_el = abs(self.__ent_cont[0].get_mode_coord().shape[0]
- self.__ent_cont[1].get_mode_coord().shape[0])
# define the left and right bound
bound_left = np.zeros(shape=(n_shared_el + not_shared_el, 2))
bound_right = np.zeros(shape=(n_shared_el + not_shared_el, 2))
# Calculate the values of the bounds for the same number of bound points on the left and right
# side
if n_shared_el > 1:
# init bounds by filling common places
bound_left[:self.__ent_cont[0].get_mode_coord().shape[0]] = self.__ent_cont[0].get_mode_coord()
bound_right[:self.__ent_cont[1].get_mode_coord().shape[0]] = self.__ent_cont[1].get_mode_coord()
# if the right bound [1] has more elements
if self.__ent_cont[0].get_mode_coord().shape[0] < self.__ent_cont[1].get_mode_coord().shape[0]:
bound_left[n_shared_el:, :] = bound_left[n_shared_el - 1, :]
# if the left bound [0] has more elements
elif self.__ent_cont[0].get_mode_coord().shape[0] > self.__ent_cont[1].get_mode_coord().shape[0]:
bound_right[n_shared_el:, :] = bound_right[n_shared_el - 1, :]
# Calculate the center line and the distance s
calc_center_line = helper_funcs.src.ssm.calc_center_line(bound_l=bound_left,
bound_r=bound_right)
# -------------------------------- calculate lane based coordinates for ego (for TTC) --------------------------
# calculate the lane based coordinates for all vehicles expect the ego vehicle
vehicle_ego_info = None
# calculate the lane based coordinates for the ego vehicle
if calc_center_line is not None and self.__ent_cont[2].TYPE_VEHICLE and self.__ent_cont[2].TYPE_EGO \
and self.__ent_cont[2].data_exp is not None:
# init lane based position for each point in data_exp
ego_pos_lane = np.zeros((self.__ent_cont[2].data_exp.shape[0], 3))
# for each point in data_exp calculate the lane based coordinates (lane_pos holds n, s, track angle)
for i in range(int(self.__ent_cont[2].data_exp.shape[0])):
ego_pos_lane[i, 0:3] = helper_funcs.src.ssm.global_2_lane_based(pos=self.__ent_cont[2].data_exp[i][1:3],
center_line=calc_center_line[0],
s_course=calc_center_line[1])
# calculate the value of position and speed for defined increment
vehicle_ego_info = helper_funcs.src.ssm.timestamp_info(lane_based_poses=ego_pos_lane,
covered_distance=self.__ent_cont[2].data_exp[:, 0],
velocity=self.__ent_cont[2].data_exp[:, 5],
t_increment=self.__config.getfloat('SAFETY',
'ssm_increment'),
t_horizon=self.__config.getfloat('SAFETY',
'ssm_horizon'))
# for all entities
for obj in self.__ent_cont:
# if entity is a vehicle
if obj.TYPE_VEHICLE:
# -------------------------------- update (if) or reset (else) plot ------------------------------------
if obj.get_mode_coord() is not None and obj.data_exp is not None:
# skip plot update, if data did not change; continue if the plot has changed or is forced to update
if obj.data_vel_coord is None or max(obj.data_exp[:, 5]) == 0.0 \
or self.__radio.value_selected == obj.id or self.__plot_all_vehicles \
or all_veh_text_need_update or force_update:
# ------------------------------ calculate velocity and acceleration ---------------------------
# if more than two coordinates and velocity profile unset or changed (set to zeros by path plan)
if obj.get_mode_coord().size > 2 and (max(obj.data_exp[:, 5]) == 0.0
or obj.data_vel_coord is None):
obj.data_vel_coord = np.copy(obj.get_mode_coord())
# calculate velocity profile
vx = tph.calc_vel_profile.calc_vel_profile(ggv=self.__ggv,
ax_max_machines=self.__ax_max_machines,
kappa=obj.data_exp[:, 4],
el_lengths=np.diff(obj.data_exp[:, 0]),
mu=np.ones(obj.data_exp.shape[0]),
v_start=500.0,
drag_coeff=self.__config.getfloat('VEHICLE',
'drag_coeff'),
m_veh=self.__config.getfloat('VEHICLE', 'm_veh'),
closed=False)
# smoothen velocity profile
vx = tph.conv_filt.conv_filt(signal=vx,
filt_window=3,
closed=False)
# calculate acceleration profile
ax = tph.calc_ax_profile.calc_ax_profile(vx_profile=vx,
el_lengths=np.diff(obj.data_exp[:, 0]))
# store vx and ax to array
obj.data_exp[:, 5] = vx
obj.data_exp[:, 6] = np.concatenate((ax, [0]))
else:
# recalculate ax for given vx profile