-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.py
executable file
·985 lines (769 loc) · 33.4 KB
/
main.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
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Krakrobot Python Simulator
Krakrobot 2014 Qualifications simulator.
Many thanks to udacity.com:
https://www.udacity.com/wiki/CS373%20Visualizing%20Maze%20Driving,
we have reused visualisation code and the general idea while implementing
this simulator.
"""
from optparse import OptionParser
from Queue import Queue
import time
import os
from threading import Thread
from threading import Event
import datetime
from PyQt4 import QtGui, QtCore, QtSvg
from simulator import KrakrobotSimulator
from robot_controller import compile_robot
from visualisation import PrepareFrame, RenderAnimatedPart,\
RenderFrameTemplate, Save, fill_visualisation_descriptor
from defines import *
__authors__ = u'Konrad Talik, Stanisław Jastrzębski'
__copyright__ = 'Copyright 2013-2014,\
Jagiellonian University Robotics Interest Group'
__license__ = 'MIT'
__version__ = '0.0.1a'
__maintainer__ = 'Konrad Talik'
# Please report bugs in GUI to this email
__email__ = '[email protected]'
# or on https://github.com/uj-robotics/Krakrobot2014Qualifications/issues
# For bugs in simulator itself [simulator.py]
# please report to staszek.jastrzebski<at>gmail.com
# or on https://github.com/uj-robotics/Krakrobot2014Qualifications/issues
__status__ = 'Development'
__about__ = """This simulator is being developed for Krakrobot \
robotics and artificial intelligence competition. \
Visit website for further information."""
__website__ = 'www.krakrobot.pl'
APP_NAME = 'Krakrobot Simulator'
APP_FULL_NAME = APP_NAME + ' ' + __version__
MSG_EMP = '-> '
DEFAULT_ANIMATION_RATE = 10
graphicsmutex = QtCore.QMutex(QtCore.QMutex.Recursive)
frame_change_mutex = QtCore.QMutex(QtCore.QMutex.Recursive)
def create_parser():
""" Configure options and return parser object """
parser = OptionParser()
parser.add_option(
"-c",
"--command_line",
dest="command_line",
action="store_true",
default=False,
help="Run simulation without visualisation"
)
parser.add_option(
"-m",
"--map",
dest="map",
default="maps/3.map",
help="Map that will be run after hitting Start Simulation button, "
"or in command_line mode after running the program"
)
parser.add_option(
"-r",
"--robot",
dest="robot",
default="examples/omit_collisions_example.py",
help="Robot that will be compiled and run"
)
parser.add_option(
"--steering_noise",
dest="steering_noise",
default=0.0004,
type="float",
help="Sigma of gaussian noise applied to turning motion"
)
parser.add_option(
"--sonar_noise",
dest="sonar_noise",
default=0.0015,
type="float",
help="Sigma of gaussian noise applied to sensed distance by sonar"
)
parser.add_option(
"--gps_noise",
dest="measurement_noise",
default=0.1,
type="float",
help="Sigma of gaussian noise applied to the sensed GPS position"
)
parser.add_option(
"--gps_delay",
dest="gps_delay",
default=2.0,
type="float",
help="Time consumption (in simulation time units) of GPS"
)
parser.add_option(
"--distance_noise",
dest="distance_noise",
default=0.001,
type="float",
help="Sigma of gaussian noise applied to forward motion"
)
parser.add_option(
"--speed",
dest="speed",
default=5.0,
type="float",
help="Speed of the robot (i.e. units/simulation second)")
parser.add_option(
"--turning_speed",
dest="turning_speed",
default=1.0,
type="float",
help="Turning speed of the robot (i.e. rad/simulation second)"
)
parser.add_option(
"--execution_cpu_time_limit",
dest="execution_cpu_time_limit",
default=100.0,
type="float",
help="Execution CPU time limit"
)
parser.add_option(
"--simulation_time_limit",
dest="simulation_time_limit",
default=100000.0,
type="float",
help="Simulation time limit (in virtual time units)"
)
parser.add_option(
"--frame_dt",
dest="frame_dt",
default=1,
type="float",
help="How often (in simulation time units) to produce a frame"
)
parser.add_option(
"--iteration_write_frequency",
dest="iteration_write_frequency",
default=1000,
type="int",
help="How often (number of ticks of simulator) to report simulation"
" status"
)
return parser
parser = create_parser()
(options, args) = parser.parse_args()
print options, args
simulator_params = {"visualisation": not options.command_line,
"speed": options.speed,
"distance_noise": options.distance_noise,
"steering_noise": options.steering_noise,
"sonar_noise": options.sonar_noise,
"measurement_noise": options.measurement_noise,
"turning_speed":options.turning_speed,
"execution_cpu_time_limit": options.execution_cpu_time_limit,
"simulation_time_limit":options.simulation_time_limit,
"frame_dt":options.frame_dt,
"iteration_write_frequency":options.iteration_write_frequency,
"gps_delay":options.gps_delay,
"robot_controller_class": compile_robot(options.robot)[0],
"map": options.map
}
class SimulationThread(QtCore.QThread):
"""KrakrobotSimulator threading"""
simulator = None
def set_simulator(self, simulator):
self.simulator = simulator
def run(self):
"""Running KrakrobotSimulator simulation"""
print "Simulation has finished. Results: {0}".format(self.simulator.run())
class KrakrobotBoardAnimation(QtGui.QGraphicsView):
"""KrakrobotSimulator board animation painting widget"""
status_bar_message = QtCore.pyqtSignal(str)
simulation_thread = None
# Interval (ms) of every animation_update timer
refresh_rate = 1000/DEFAULT_ANIMATION_RATE
# Number of frames skipped in animation_update timer
#NOTE: Ths value is being incremented when when refresh_rate is too small
animation_speed = 1
frame_template = ''
frames = []
current_frame = 0
frame_count = 0
simulator = None
animation_started = False
animation_paused = False
def __init__(self, simulator, parent):
super(KrakrobotBoardAnimation, self).__init__(parent)
self.init_ui()
self.simulator = simulator
def init_ui(self):
self.frames_timer = QtCore.QTimer(self)
self.frames_timer.timeout.connect(self.frames_update)
self.animation_timer = QtCore.QTimer(self)
self.animation_timer.timeout.connect(self.animation_update)
self.setScene(QtGui.QGraphicsScene(self))
self.setTransformationAnchor(self.AnchorUnderMouse)
self.setDragMode(self.ScrollHandDrag)
self.setCacheMode(self.CacheBackground)
self.setViewportUpdateMode(self.NoViewportUpdate)
def clear_board(self):
"""Clear and prepare board for animation"""
scene = self.scene()
scene.clear()
self.resetTransform()
self.xml_stream_reader = QtCore.QXmlStreamReader()
if self.frame_template:
self.xml_stream_reader = QtCore.QXmlStreamReader(self.frame_template)
self.svg_renderer = QtSvg.QSvgRenderer(self.xml_stream_reader)
self.svg_item = QtSvg.QGraphicsSvgItem()
self.svg_item.setSharedRenderer(self.svg_renderer)
self.svg_item.setFlags(QtGui.QGraphicsItem.ItemClipsToShape)
self.svg_item.setCacheMode(QtGui.QGraphicsItem.NoCache)
self.svg_item.setZValue(0)
scene.addItem(self.svg_item)
scene.setSceneRect(self.svg_item.boundingRect().adjusted(-10, -10, 10, 10))
def start(self):
"""Start simulation process"""
if self.animation_paused:
return
self.animation_started = True
self.frame_template = ''
self.frames = []
self.current_frame = 0
self.frame_count = 0
self.animation_started = True
self.animation_paused = False
self.simulation_thread = SimulationThread()
self.simulation_thread.finished.connect(self.parent().parent().simulation_finished)
self.clear_board()
self.simulation_thread.set_simulator(self.simulator)
self.simulation_thread.start()
self.status_bar_message.emit('Simulation started...')
self.frames_timer.start(0)
self.animation_timer.start(self.refresh_rate)
def pause_animation(self):
"""Pause animation process"""
if not self.animation_started:
return
self.animation_paused = not self.animation_paused
if self.animation_paused:
self.animation_timer.stop()
self.status_bar_message.emit('Animation paused.')
else:
self.animation_timer.start(self.refresh_rate)
self.status_bar_message.emit('Animation played...')
def terminate_simulation(self):
self.simulation_thread.terminate()
self.simulator.terminate()
self.frames_timer.stop()
def frames_update(self):
"""Update collection and GUI with current simulator frames data
This method is an event of self.frames_timer timeout
"""
if self.simulator:
try:
sim_data = self.simulator.get_next_frame_nowait()
except Exception:
if self.simulator.finished:
self.frames_timer.stop()
return
fill_visualisation_descriptor(sim_data)
if self.frame_template == '':
self.frame_template = RenderFrameTemplate(sim_data)
self.clear_board()
svg_data = RenderAnimatedPart(sim_data)
self.frames.append(svg_data)
self.frame_count += 1
# GUI update #
main_window = self.parent().parent()
main_window.update_frame_count(self.frame_count)
def animation_update(self):
"""Update GUI with current animation frame
This method is an event of self.animation_timer timeout
"""
if len(self.frames) > 0:
if self.current_frame+1 > self.frame_count:
return
svg_data = PrepareFrame(self.frame_template,self.frames[self.current_frame])
self.xml_stream_reader.clear()
self.xml_stream_reader.addData(svg_data)
self.svg_renderer.load(self.xml_stream_reader)
scene = self.scene()
self.svg_item.setSharedRenderer(self.svg_renderer)
self.svg_item.setFlags(QtGui.QGraphicsItem.ItemClipsToShape)
self.svg_item.setCacheMode(QtGui.QGraphicsItem.NoCache)
self.svg_item.setZValue(0)
scene.update()
scene.setSceneRect(self.svg_item.boundingRect().adjusted(-10, -10, 10, 10))
if not self.animation_paused:
previous_frame = self.current_frame
self.current_frame += self.animation_speed
# GUI update #
main_window = self.parent().parent()
main_window.update_current_frame(self.current_frame)
# Animation output update - we must calculate frames we have skipped
for frame in range(previous_frame, self.current_frame+1):
main_window.check_and_update_animation_console(frame)
if self.refresh_rate >= 10:
self.animation_timer.setInterval(self.refresh_rate)
else:
self.animation_speed = 10/self.refresh_rate
def new_simulator(self, simulator):
self.simulator = simulator
def wheelEvent(self, event):
factor = pow(1.2, event.delta()/240.0)
self.scale(factor, factor)
event.accept()
class MainWindow(QtGui.QMainWindow):
"""Main window (all-in-one window)"""
text_edit_width = 80
text_edit_height = 30
def __init__(self, simulator):
super(MainWindow, self).__init__()
self.simulator = simulator
self.update_slider = True
self.currently_simulating = False
self.console_dict = {}
self.console_timer = QtCore.QTimer(self)
self.console_timer.timeout.connect(self._update_console_log)
self._init_ui(simulator)
def _init_ui(self, simulator):
self.window_icon = QtGui.QIcon( './pics/iiujrobotics.svg')
self.setWindowIcon(self.window_icon)
### Toolbar ###
main_toolbar = self.addToolBar('Krakrobot Simulator')
self.setWindowTitle(APP_FULL_NAME)
self.status_bar_message('Welcome to ' + APP_FULL_NAME + '!')
main_toolbar.setToolButtonStyle(QtCore.Qt.ToolButtonTextBesideIcon)
self.start_sim_action = main_toolbar.addAction(
QtGui.QIcon.fromTheme('system-run'),
'Start Simulation'
)
self.start_sim_action.triggered.connect(self._run_simulation)
self.terminate_sim_action = main_toolbar.addAction(
QtGui.QIcon.fromTheme('process-stop'),
'Terminate'
)
self.terminate_sim_action.triggered.connect(self._terminate_simulation)
#TODO: maximum lines for QPlainTextEdit = 1
params_toolbar = self.addToolBar('Simulator parameters')
steering_noise_label = QtGui.QLabel('steering_noise: ')
params_toolbar.addWidget(steering_noise_label)
self.steering_noise_edit = QtGui.QPlainTextEdit(str(simulator_params['steering_noise']))
self.steering_noise_edit.setMaximumWidth(self.text_edit_width)
self.steering_noise_edit.setMaximumHeight(self.text_edit_height)
params_toolbar.addWidget(self.steering_noise_edit)
self.steering_noise_edit.textChanged.connect(self._update_steering_noise)
sonar_noise_label = QtGui.QLabel('sonar_noise: ')
params_toolbar.addWidget(sonar_noise_label)
self.sonar_noise_edit = QtGui.QPlainTextEdit(str(simulator_params['sonar_noise']))
self.sonar_noise_edit.setMaximumWidth(self.text_edit_width)
self.sonar_noise_edit.setMaximumHeight(self.text_edit_height)
params_toolbar.addWidget(self.sonar_noise_edit)
self.sonar_noise_edit.textChanged.connect(self._update_sonar_noise)
distance_noise_label = QtGui.QLabel('distance_noise: ')
params_toolbar.addWidget(distance_noise_label)
self.distance_noise_edit = QtGui.QPlainTextEdit(str(simulator_params['distance_noise']))
self.distance_noise_edit.setMaximumWidth(self.text_edit_width)
self.distance_noise_edit.setMaximumHeight(self.text_edit_height)
params_toolbar.addWidget(self.distance_noise_edit)
self.distance_noise_edit.textChanged.connect(self._update_distance_noise)
measurement_noise_label = QtGui.QLabel('measurement_noise: ')
params_toolbar.addWidget(measurement_noise_label)
self.measurement_noise_edit = QtGui.QPlainTextEdit(str(simulator_params['measurement_noise']))
self.measurement_noise_edit.setMaximumWidth(self.text_edit_width)
self.measurement_noise_edit.setMaximumHeight(self.text_edit_height)
params_toolbar.addWidget(self.measurement_noise_edit)
self.measurement_noise_edit.textChanged.connect(self._update_measurement_noise)
frame_dt_label = QtGui.QLabel('frame_dt: ')
params_toolbar.addWidget(frame_dt_label)
self.frame_dt_edit = QtGui.QPlainTextEdit(str(simulator_params['frame_dt']))
self.frame_dt_edit.setMaximumWidth(self.text_edit_width)
self.frame_dt_edit.setMaximumHeight(self.text_edit_height)
params_toolbar.addWidget(self.frame_dt_edit)
self.frame_dt_edit.textChanged.connect(self._update_frame_dt)
speed_label = QtGui.QLabel('speed: ')
params_toolbar.addWidget(speed_label)
self.speed_edit = QtGui.QPlainTextEdit(str(simulator_params['speed']))
self.speed_edit.setMaximumWidth(self.text_edit_width)
self.speed_edit.setMaximumHeight(self.text_edit_height)
params_toolbar.addWidget(self.speed_edit)
self.speed_edit.textChanged.connect(self._update_speed)
turning_speed_label = QtGui.QLabel('turning_speed: ')
params_toolbar.addWidget(turning_speed_label)
self.turning_speed_edit = QtGui.QPlainTextEdit(str(simulator_params['turning_speed']))
self.turning_speed_edit.setMaximumWidth(self.text_edit_width)
self.turning_speed_edit.setMaximumHeight(self.text_edit_height)
params_toolbar.addWidget(self.turning_speed_edit)
self.turning_speed_edit.textChanged.connect(self._update_turning_speed)
execution_cpu_time_limit_label = QtGui.QLabel('execution_cpu_time_limit: ')
params_toolbar.addWidget(execution_cpu_time_limit_label)
self.execution_cpu_time_limit_edit = QtGui.QPlainTextEdit(str(simulator_params['execution_cpu_time_limit']))
self.execution_cpu_time_limit_edit.setMaximumWidth(self.text_edit_width)
self.execution_cpu_time_limit_edit.setMaximumHeight(self.text_edit_height)
params_toolbar.addWidget(self.execution_cpu_time_limit_edit)
self.execution_cpu_time_limit_edit.textChanged.connect(self._update_execution_cpu_time_limit)
simulation_time_limit_label = QtGui.QLabel('simulation_time_limit: ')
params_toolbar.addWidget(simulation_time_limit_label)
self.simulation_time_limit_edit = QtGui.QPlainTextEdit(str(simulator_params['simulation_time_limit']))
self.simulation_time_limit_edit.setMaximumWidth(self.text_edit_width)
self.simulation_time_limit_edit.setMaximumHeight(self.text_edit_height)
params_toolbar.addWidget(self.simulation_time_limit_edit)
self.simulation_time_limit_edit.textChanged.connect(self._update_simulation_time_limit)
gps_delay_label = QtGui.QLabel('gps_delay: ')
params_toolbar.addWidget(gps_delay_label)
self.gps_delay_edit = QtGui.QPlainTextEdit(str(simulator_params['gps_delay']))
self.gps_delay_edit.setMaximumWidth(self.text_edit_width)
self.gps_delay_edit.setMaximumHeight(self.text_edit_height)
params_toolbar.addWidget(self.gps_delay_edit)
self.gps_delay_edit.textChanged.connect(self._update_gps_delay)
iteration_write_frequency_label = QtGui.QLabel('iteration_write_frequency: ')
params_toolbar.addWidget(iteration_write_frequency_label)
self.iteration_write_frequency_edit = QtGui.QPlainTextEdit(str(simulator_params['iteration_write_frequency']))
self.iteration_write_frequency_edit.setMaximumWidth(self.text_edit_width)
self.iteration_write_frequency_edit.setMaximumHeight(self.text_edit_height)
params_toolbar.addWidget(self.iteration_write_frequency_edit)
self.iteration_write_frequency_edit.textChanged.connect(self._update_iteration_write_frequency)
simulation_layout = QtGui.QVBoxLayout()
self.board_animation = KrakrobotBoardAnimation(self.simulator, self)
self.board_animation.status_bar_message[str].connect(
self.status_bar_message
)
simulation_layout.addWidget(self.board_animation)
### Playbock Layout ###
playback_layout = QtGui.QHBoxLayout()
playback_toolbar = QtGui.QToolBar()
speed_label = QtGui.QLabel('Anim. rate: ')
playback_toolbar.addWidget(speed_label)
self.speed_box = QtGui.QSpinBox(self)
self.speed_box.setRange(1, 1000)
self.speed_box.setValue(DEFAULT_ANIMATION_RATE)
self.speed_box.setToolTip('Change animation rate')
self.speed_box.valueChanged.connect(self._speed_value_changed)
playback_toolbar.addWidget(self.speed_box)
play_progress_action = playback_toolbar.addAction(
QtGui.QIcon.fromTheme('media-playback-start'),
'Play progress animation'
)
play_progress_action.triggered.connect(self._play_progress_animation)
pause_progress_action = playback_toolbar.addAction(
QtGui.QIcon.fromTheme('media-playback-pause'),
'Pause progress animation'
)
pause_progress_action.triggered.connect(self._pause_progress_animation)
skip_backward_action = playback_toolbar.addAction(
QtGui.QIcon.fromTheme('media-skip-backward'),
'Skip to the beginning'
)
skip_backward_action.triggered.connect(self._skip_backward)
skip_forward_action = playback_toolbar.addAction(
QtGui.QIcon.fromTheme('media-skip-forward'),
'Skip to the end'
)
skip_forward_action.triggered.connect(self._skip_forward)
playback_toolbar.setMaximumWidth(playback_toolbar.sizeHint().width())
playback_layout.addWidget(playback_toolbar)
self.scroll_bar = QtGui.QScrollBar(QtCore.Qt.Horizontal)
self.scroll_bar.sliderPressed.connect(self._hold_slider_updates)
self.scroll_bar.sliderReleased.connect(
self._send_slider_value_and_continue_updates
)
playback_layout.addWidget(self.scroll_bar)
self.scroll_text = QtGui.QLabel('-/-', self)
self.scroll_text.current_frame = '-'
self.scroll_text.frame_count = '-'
self.scroll_text.setMaximumWidth(self.scroll_text.sizeHint().width())
playback_layout.addWidget(self.scroll_text)
playback_layout_widget = QtGui.QWidget()
playback_layout_widget.setLayout(playback_layout)
playback_layout_widget.setMaximumHeight(
playback_layout_widget.sizeHint().height()
)
simulation_layout.addWidget(playback_layout_widget)
self.simulation_layout_widget = QtGui.QWidget()
self.simulation_layout_widget.setLayout(simulation_layout)
self.setCentralWidget(self.simulation_layout_widget)
### Widgets (as named in this application) ###
self.console_font = QtGui.QFont('Monospace', 10)
self.output_console = QtGui.QTextBrowser()
self.output_console.setFont(self.console_font)
self.console_dock_widget = QtGui.QDockWidget(
' &Simulation output console ',
self
)
self.console_dock_widget.setWidget(self.output_console)
self.addDockWidget(
QtCore.Qt.BottomDockWidgetArea,
self.console_dock_widget
)
self.animation_console = QtGui.QTextBrowser()
self.animation_console.setFont(self.console_font)
self.animation_console_dock_widget = QtGui.QDockWidget(
' &Animation output console ',
self
)
self.animation_console_dock_widget.setWidget(self.animation_console)
self.addDockWidget(
QtCore.Qt.BottomDockWidgetArea,
self.animation_console_dock_widget
)
### Menu ###
map_menu = QtGui.QMenu('&Map', self)
self.load_map_action = map_menu.addAction('&Load from file...')
self.load_map_action.triggered.connect(self.load_map)
self.menuBar().addMenu(map_menu)
robot_menu = QtGui.QMenu('&Robot', self)
self.open_source_action = robot_menu.addAction('&Load source code file...')
self.open_source_action.triggered.connect(self.open_source)
self.menuBar().addMenu(robot_menu)
widgets_menu = QtGui.QMenu('&Widgets', self)
self.console_action = widgets_menu.addAction(
self.console_dock_widget.toggleViewAction()
)
self.animation_console_action = widgets_menu.addAction(
self.animation_console_dock_widget.toggleViewAction()
)
self.menuBar().addMenu(widgets_menu)
help_menu = QtGui.QMenu('&Help', self)
self.about_action = help_menu.addAction(
QtGui.QIcon.fromTheme('help-about'),
'&About...'
)
self.about_action.triggered.connect(self.about_window)
self.menuBar().addMenu(help_menu)
# Actions that we need to disable when simulating
self.conflicting_with_sim = [
self.start_sim_action,
self.steering_noise_edit,
self.sonar_noise_edit,
self.distance_noise_edit,
self.measurement_noise_edit,
self.speed_edit,
self.turning_speed_edit,
self.execution_cpu_time_limit_edit,
self.simulation_time_limit_edit,
self.frame_dt_edit,
self.gps_delay_edit,
self.iteration_write_frequency_edit
]
def status_bar_message(self, message):
self.statusBar().showMessage(message)
def update_frame_count(self, frame_count):
if self.update_slider:
self.scroll_bar.setMaximum(frame_count)
self.scroll_text.frame_count = str(frame_count)
self.scroll_bar_text()
def update_current_frame(self, current_frame):
#if self.update_slider:
self.scroll_bar.setValue(current_frame)
self.scroll_text.current_frame = str(current_frame)
self.scroll_bar_text()
def scroll_bar_text(self):
self.scroll_text.setText('frame '+str(
self.scroll_text.current_frame
)+'/'+str(
self.scroll_text.frame_count
)
)
self.scroll_text.setMaximumWidth(self.scroll_text.sizeHint().width())
def load_map(self):
file_name = QtGui.QFileDialog.getOpenFileName(
self, 'Load map from file...', '.', 'Krakrobot maps (*.map)'
)
if os.path.isfile(file_name):
simulator_params['map'] = str(file_name)
self.status_bar_message(
'Map loaded from ' + str(file_name)
)
else:
self.status_bar_message(
'File does not exist: ' + str(file_name)
)
def open_source(self):
file_name = QtGui.QFileDialog.getOpenFileName(
self, 'Open robot source code file...', '.',
'Python code (*.py)'
)
try:
compilation = compile_robot(str(file_name))[0]
except Exception as error:
self.status_bar_message(
MSG_EMP + 'Robot source code compiling error: ' + str(error)
)
return -1
simulator_params['robot_controller_class'] = compilation
self.status_bar_message(
'Robot source code loaded from ' + str(file_name)
)
def about_window(self):
QtGui.QMessageBox.about(
self,
'About Krakrobot Python Simulator ' + __version__,
QtCore.QString(__about__+'\n') + \
QtCore.QString('\n'+__website__+'\n') + \
QtCore.QString('\n'+__authors__+'\n') + \
QtCore.QString(
'https://github.com/uj-robotics/Krakrobot2014Qualifications\n'
) + \
QtCore.QString('\nLicense: '+__license__+'\n') + \
QtCore.QString(
"""Copyright (c) 2013-2014 """
"""Jagiellonian University Robotics Interest Group,"""
"""http://www.robotics.ii.uj.edu.pl/"""
)
)
def _speed_value_changed(self):
self.board_animation.refresh_rate = \
1000/self.speed_box.value()
def _hold_slider_updates(self):
self.update_slider = False
def _continue_slider_updates(self):
self.update_slider = True
def _send_scroll_bar_value(self):
"""Send scroll bar value to animation widget"""
frame_change_mutex.lock()
self.board_animation.current_frame = self.scroll_bar.value()
current_frame = self.scroll_bar.value()
self.board_animation.animation_update()
frame_change_mutex.unlock()
def _send_slider_value_and_continue_updates(self):
self._send_scroll_bar_value()
self._continue_slider_updates()
def _play_progress_animation(self):
"""Play animation process"""
if self.board_animation.animation_paused:
self.board_animation.pause_animation()
def _toggle_pause_progress_animation(self):
self.board_animation.pause_animation()
def _pause_progress_animation(self):
if not self.board_animation.animation_paused:
self.board_animation.pause_animation()
def _skip_forward(self):
self.scroll_bar.setValue(self.scroll_bar.maximum()-1)
self._send_scroll_bar_value()
self._pause_progress_animation()
def _skip_backward(self):
self.scroll_bar.setValue(self.scroll_bar.minimum())
self._send_scroll_bar_value()
self._pause_progress_animation()
def _run_simulation(self):
self.currently_simulating = True
self._play_progress_animation()
for action in self.conflicting_with_sim:
action.setEnabled(False)
self._reconstruct_simulator()
self.board_animation.start()
self.console_timer.start(1)
def _terminate_simulation(self):
self.board_animation.terminate_simulation()
self.currently_simulating = False
self.simulation_finished()
# Communicative purposes
self._pause_progress_animation()
def simulation_finished(self):
self.status_bar_message(MSG_EMP+'Simulation has finished!')
self.console_timer.stop()
for action in self.conflicting_with_sim:
action.setEnabled(True)
def _save_code(self):
data = self.code_text_edit.toPlainText()
self._save_to_file(self.code_text_edit.file_name, data)
def _save_to_file(self, file_name, data):
output_file = open(file_name, 'w')
with output_file:
output_file.write(str(data))
def _read_file_data(self, file_name):
input_file = open(file_name, 'r')
with input_file:
return input_file.read()
def _reconstruct_simulator(self):
self.simulator = KrakrobotSimulator(**simulator_params)
self.board_animation.new_simulator(
self.simulator
)
def _update_console_log(self):
logsc = len(self.board_animation.simulator.get_logs())
if logsc > 0:
new_line = self.board_animation.simulator.get_logs()[logsc-1]
new_line_split = new_line.split(':\n')
line_dict = eval(new_line_split[0])
self.console_dict[ line_dict['frame'] ] = new_line
self.output_console.append( str(
new_line
)
)
self.output_console.verticalScrollBar().setSliderPosition(
self.output_console.verticalScrollBar().maximum()
)
def check_and_update_animation_console(self, frame):
if self.console_dict.has_key(frame):
self.animation_console.append(
self.console_dict[frame]
)
def closeEvent(self, event):
self._terminate_simulation()
def _update_steering_noise(self):
simulator_params['steering_noise'] = \
float(self.steering_noise_edit.toPlainText())
def _update_sonar_noise(self):
simulator_params['sonar_noise'] = \
float(self.sonar_noise_edit.toPlainText())
def _update_distance_noise(self):
simulator_params['distance_noise'] = \
float(self.distance_noise_edit.toPlainText())
def _update_measurement_noise(self):
simulator_params['measurement_noise'] = \
float(self.measurement_noise_edit.toPlainText())
def _update_speed(self):
simulator_params['speed'] = \
float(self.speed_edit.toPlainText())
def _update_turning_speed(self):
simulator_params['turning_speed'] = \
float(self._edit.toPlainText())
def _update_execution_cpu_time_limit(self):
simulator_params['execution_cpu_time_limit'] = \
float(self.execution_cpu_time_limit_edit.toPlainText())
def _update_simulation_time_limit(self):
simulator_params['simulation_time_limit'] = \
float(self.simulation_time_limit_edit.toPlainText())
def _update_simulation_dt(self):
simulator_params['simulation_dt'] = \
float(self.simulation_dt_edit.toPlainText())
def _update_frame_dt(self):
simulator_params['frame_dt'] = \
float(self.frame_dt_edit.toPlainText())
def _update_gps_delay(self):
simulator_params['gps_delay'] = \
float(self.gps_delay_edit.toPlainText())
def _update_iteration_write_frequency(self):
simulator_params['iteration_write_frequency'] = \
float(self.iteration_write_frequency_edit.toPlainText())
class SimulatorGUI(object):
"""GUI master class"""
simulator = None
application_thread = None
qt_app = None
def __init__(self, argv, simulator):
""" Initialize GUI
@param argv - program arguments values
@param simulator - KrakrobotSimulator object
"""
self.simulator = simulator
self.qt_app = QtGui.QApplication(argv)
def run(self):
main_window = MainWindow(self.simulator)
main_window.showMaximized()
sys.exit(self.qt_app.exec_())
import sys
import json
def main():
if not options.command_line:
simulator = KrakrobotSimulator(**simulator_params)
gui = SimulatorGUI(sys.argv, simulator)
gui.run()
else:
simulator = KrakrobotSimulator(simulation_dt=0.0, **simulator_params)
print "Running simulator"
results = simulator.run()
print "Finished running simulator"
print "Simulation has finished. Results:\n{0}".format(json.dumps(results))
if __name__ == '__main__':
main()