-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathaeos_dockwidget.py
1169 lines (987 loc) · 56.4 KB
/
aeos_dockwidget.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
# -*- coding: utf-8 -*-
"""
/***************************************************************************
AeosDockWidget
A QGIS plugin
Plugin for LiDAR Simulator HELIOS++
Generated by Plugin Builder: http://g-sherman.github.io/Qgis-Plugin-Builder/
-------------------
begin : 2021-11-18
git sha : $Format:%H$
copyright : (C) 2021 by Mark Searle
email : [email protected]
***************************************************************************/
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
"""
# Imports
import os
import sys
import traceback
import time
from qgis.PyQt import QtGui, QtWidgets, uic
from qgis.PyQt.QtCore import pyqtSignal, QUrl, QThread, QObject, Qt, QVariant
from qgis.core import *
from qgis.gui import QgsFileWidget
from qgis.utils import iface
import xml.etree.ElementTree as ET
FORM_CLASS, _ = uic.loadUiType(os.path.join(
os.path.dirname(__file__), 'aeos_dockwidget_base.ui'))
FORM_CLASS_2_popup, _ = uic.loadUiType(os.path.join(
os.path.dirname(__file__), 'scanner_config.ui'))
FORM_CLASS_3_popup, _ = uic.loadUiType(os.path.join(
os.path.dirname(__file__), 'data_gen_config.ui'))
def warning_box(title, info_text, main_text, cancel_button=1):
def msgbtn(i):
pass
msg = QtWidgets.QMessageBox()
msg.setText(main_text)
msg.setIcon(QtWidgets.QMessageBox.Warning)
msg.setInformativeText(info_text)
msg.setWindowTitle(title)
if cancel_button == 1:
msg.setStandardButtons(QtWidgets.QMessageBox.Ok | QtWidgets.QMessageBox.Cancel)
elif cancel_button == 0:
msg.setStandardButtons(QtWidgets.QMessageBox.Ok)
msg.buttonClicked.connect(msgbtn)
ret_val = msg.exec_()
# Returns true if ok is clicked, else false.
if ret_val == 1024:
return True
else:
return False
class ScannerConfig(QtWidgets.QDialog, FORM_CLASS_2_popup):
def __init__(self, AeosDockWidget):
super(ScannerConfig, self).__init__(AeosDockWidget)
self.setupUi(self)
class DataGenConfig(QtWidgets.QDialog, FORM_CLASS_3_popup):
def __init__(self, AeosDockWidget):
super(DataGenConfig, self).__init__(AeosDockWidget)
self.setupUi(self)
self.config_scan_xml_error.setHidden(True)
self.config_scan_xml_error.setText('<span style="color:red"> * Invalid Scanner XML</span>')
self.config_scene_xml_error.setHidden(True)
self.config_scene_xml_error.setText('<span style="color:red"> * Invalid Scene XML</span>')
self.config_scene_input.fileChanged.connect(self.config_parse_scene)
self.config_scanner_input.fileChanged.connect(self.config_parse_scanner)
self.config_scanners = {}
self.config_scenes = {}
def closeEvent(self, event):
pass
def config_parse_scene(self):
# Reset error messages.
self.config_scene_xml_error.setHidden(True)
self.config_scene_xml_error.setText('<span style="color:red"> * Invalid Scene XML</span>')
# Clear combo box.
self.scene_selection_2.clear()
# Change locked in field back to combobox. Only necessary when user has previously locked in a scanner.
#self.selected_scene.setHidden(True)
#self.scene_selection.setHidden(False)
try:
# Parse XML and extract names of scenes:
scene_root = ET.parse(self.config_scene_input.filePath()).getroot()
for scene in scene_root.findall('scene'):
self.scene_selection_2.addItem(scene.attrib['name'])
self.config_scenes[scene.attrib['name']] = scene.attrib['id']
if self.scene_selection_2.count() == 0:
# Give error message if no scanner options are found.
self.config_scene_xml_error.setText('<span style="color:red"> * No valid scenes found</span>')
self.config_scene_xml_error.setHidden(False)
except Exception as err:
# If error occurs during above steps, stop function and give error message.
self.config_scene_xml_error.setHidden(False)
print(err)
return 0
def config_parse_scanner(self):
# Reset error messages.
self.config_scan_xml_error.setHidden(True)
self.config_scan_xml_error.setText('<span style="color:red"> * Invalid Scanner XML</span>')
# Clear combo box.
self.scanner_selection_2.clear()
# Change locked in field back to combobox. Only necessary when user has previously locked in a scanner.
#self.selected_scanner.setHidden(True)
#self.scanner_selection.setHidden(False)
try:
# Parse XML and extract options for scanners:
scanner_root = ET.parse(self.config_scanner_input.filePath()).getroot()
for scanner in scanner_root.findall('scanner'):
# Add name of each option to combobox.
self.scanner_selection_2.addItem(scanner.attrib['name'])
self.config_scanners[scanner.attrib['name']] = [scanner.attrib['id'], scanner.attrib['pulseFreqs_Hz'].split(','),
scanner.attrib['scanAngleMax_deg'], scanner.attrib['scanFreqMin_Hz'],
scanner.attrib['scanFreqMax_Hz']]
if self.scanner_selection_2.count() == 0:
# Give error message if no scanner options are found.
self.config_scan_xml_error.setText('<span style="color:red"> * No valid scanners found</span>')
self.config_scan_xml_error.setHidden(False)
except Exception as err:
self.config_scan_xml_error.setHidden(False)
print(err)
return 0
class DirectoryDialogue(QtWidgets.QDialog):
"""
Class for Dialogue that is used to configure HELIOS path as project variable.
"""
def __init__(self, message_text):
super().__init__()
# Set up Window
self.setWindowTitle("Set Helios Directory")
QBtn = QtWidgets.QDialogButtonBox.Ok | QtWidgets.QDialogButtonBox.Cancel
self.buttonBox = QtWidgets.QDialogButtonBox(QBtn)
self.input_dir = QgsFileWidget()
self.input_dir.setStorageMode(QgsFileWidget.StorageMode(1))
self.buttonBox.accepted.connect(self.ok_click)
self.buttonBox.rejected.connect(self.cancel_click)
self.layout = QtWidgets.QVBoxLayout()
message = QtWidgets.QLabel(message_text)
self.layout.addWidget(message)
self.layout.addWidget(self.input_dir)
self.layout.addWidget(self.buttonBox)
self.setLayout(self.layout)
def ok_click(self):
"""Function that is executed when user clicks 'ok' button."""
if self.input_dir.filePath() == "":
# If no input was given, output an error msg
label = QtWidgets.QLabel()
label.setText('<span style="color:red"> *You must select a valid directory.</span>')
label.setTextFormat(Qt.TextFormat(2))
self.layout.insertWidget(len(self.layout)-1, label)
else:
# If an input was given, set the directory as project variable.
proj = QgsProject.instance()
QgsExpressionContextUtils.setProjectVariable(proj, 'helios_directory', self.input_dir.filePath())
print("Helios Directory has been set to: " + self.input_dir.filePath())
self.accept()
# return 1
def cancel_click(self):
"""Function that is excecuted when user clicks 'cancel'. In this case, self.exec() returns 0 automatically."""
self.reject()
# return 0
class AeosDockWidget(QtWidgets.QDockWidget, FORM_CLASS):
"""
Class for main plugin window.
"""
closingPlugin = pyqtSignal()
def __init__(self, parent=None):
"""Constructor for main plugin window."""
super(AeosDockWidget, self).__init__(parent)
# Set up the ui and empty variables for the worker who will handle running the sim on another thread.
self.setupUi(self)
#self.config_window = DataGenConfig(self)
#self.config_window.closeEvent.connect(config_window_close)
self.worker = Worker("", "")
self.thread = None
self.previous_path = None
self.flight_alt = None
self.gnd_raster.addItem("")
self.gnd_raster.setCurrentIndex(0)
self.flight_alt_range.setText("20")
# Dict for platform id and type.
self.platforms = {}
self.platform_type = None
# Dict for scanners.
self.scanners = {}
# Dict for scenes.
self.scenes = {}
# Get helios path from project variable
proj = QgsProject.instance()
self.helios_dir = QgsExpressionContextUtils.projectScope(proj).variable('helios_directory')
proj = None
self.helios_dir_label.setText("""<font size="3">[{}]</font>""".format(self.helios_dir))
# Make Error msgs invisible
self.layer_error_popup.setHidden(True)
self.survey_name_error_popup.setHidden(True)
self.output_dir_error_popup.setHidden(True)
self.plat_xml_error.setHidden(True)
self.scan_xml_error.setHidden(True)
self.scene_xml_error.setHidden(True)
self.scanner_config_error.setHidden(True)
self.final_msg.setHidden(True)
self.sim_status.setHidden(True)
self.time_counter.setHidden(True)
self.sim_final_output.setHidden(True)
self.survey_path_error.setHidden(True)
self.raster_layer_error.setHidden(True)
self.tab2_general_error.setHidden(True)
self.data_gen_status.setHidden(True)
# Make selected scanner names invisible.
self.selected_platform.setHidden(True)
self.selected_scanner.setHidden(True)
self.selected_scene.setHidden(True)
# Make platform type label invisible.
self.platform_type_label.setHidden(True)
### Link buttons with functions. ###
# Survey generation and config lock-in:
self.generate_survey_button.clicked.connect(self.generate_survey)
self.lock_in_config_button.clicked.connect(self.lock_in_config)
# Parse parameter XMLs upon change in filewidget file selection window:
self.platform_input.fileChanged.connect(self.parse_platform)
self.scanner_input.fileChanged.connect(self.parse_scanner)
self.scene_input.fileChanged.connect(self.parse_scene)
# Set default values for platform and scanner.
self.platform_input.setFilePath(os.path.join(self.helios_dir, 'data\platforms.xml'))
self.parse_platform()
self.scanner_input.setFilePath(os.path.join(self.helios_dir, 'data\scanners_als.xml'))
self.parse_scanner()
# Hide ULS options in tab 2.
self.uls_widget.hide()
# Tab navigation buttons:
self.tab1_next_tab.clicked.connect(self.next_tab)
self.tab2_next_tab.clicked.connect(self.next_tab)
self.tab2_prev_tab.clicked.connect(self.prev_tab)
# Visualize survey, start simulation, stop simulation:
self.survey_vis_button.clicked.connect(self.visualize_survey)
self.start_sim.clicked.connect(self.start_sim_worker)
# Configure HELIOS path
self.path_config.clicked.connect(self.configure_helios_path)
# Open Data Gen Config
self.data_gen_config.clicked.connect(self.data_gen_configuration)
self.trajectory_refresh.clicked.connect(self.refresh_trajectory)
self.data_gen_execute.clicked.connect(self.generate_data)
# Set tooltips
self.gnd_raster.setToolTip('Specify a raster layer to maintain altitude over given layer.')
def configure_helios_path(self):
"""Allows user to redefine HELIOS directory (saved in project variable)."""
# Start directory dialogue
dialogue = DirectoryDialogue("Reconfigure your HELIOS++ directory.")
if dialogue.exec() == 0:
pass
else:
# If a new dir was selected, update class attribute and label.
proj = QgsProject.instance()
self.helios_dir = QgsExpressionContextUtils.projectScope(proj).variable('helios_directory')
self.helios_dir_label.setText("""<font size="3">[{}]</font>""".format(self.helios_dir))
def visualize_survey(self):
"""Function that takes a survey file and uses the legs to create a vector layer and load it into QGIS."""
# Hide error message.
self.survey_path_error.setHidden(True)
# In case of empty input, display error msg and stop function.
if self.survey_exec_path.filePath() == "":
self.survey_path_error.setHidden(False)
return 0
# Get survey name to be used as layer name in QGIS.
survey_root = ET.parse(self.survey_exec_path.filePath()).getroot()
survey_name = survey_root.find('survey').attrib['name']
# List for storing data on each individual leg in survey file.
trajectory = []
# Parse survey file.
survey_root = ET.parse(self.survey_exec_path.filePath()).getroot()
survey = survey_root.find('survey')
for leg in survey.findall('leg'):
# Iterate over each leg, getting platform and scanner settings of each.
platform_settings = leg.find('platformSettings')
scanner_settings = leg.find('scannerSettings')
# Append values for leg: [QGIS point geometry from x and y vals, z val, leg number, 'active' flag]
trajectory.append([QgsPoint(float(platform_settings.attrib['x']), float(platform_settings.attrib['y'])),
platform_settings.attrib['z'], len(trajectory), scanner_settings.attrib['active']])
# Create temporary vector layer to fill with features.
if "tls" in survey_root.find('survey').attrib['scanner']:
# For TLS surveys, create a multipoint layer.
vector_layer = QgsVectorLayer("MultiPoint?crs=epsg:32632", "{}".format(survey_name + '-trajectory'),
"memory")
else:
# For ALS, ULS surveys, create linestring layer.
vector_layer = QgsVectorLayer("LineString?crs=epsg:32632", "{}".format(survey_name + '-trajectory'),
"memory")
# Attributes are id, leg_number, z_value.
pr = vector_layer.dataProvider()
pr.addAttributes([QgsField("id", QVariant.Int),
QgsField("leg_number", QVariant.Int),
QgsField("z_value", QVariant.Double)])
vector_layer.updateFields()
# List for storing each individual feature, corresponding to one leg in simulation.
features = []
for i in range(len(trajectory)):
feature = []
# Iterate over points in trajectory. If active flag is true, following leg point is also added to feature.
# If false, new feature is created from previous points and is added to 'features'.
# Then, keeps iterating over remaining points in trajectory.
for trajectory_point in trajectory:
if trajectory_point[3] == 'true':
feature.append(trajectory_point)
if trajectory_point[3] == 'false':
feature.append(trajectory_point)
break
if len(feature) > 0:
features.append(feature)
trajectory = trajectory[len(feature):]
# Create QGIS feature for each feature in 'features' | id is counter for features
id = 0
for feature in features:
new_feature = QgsFeature()
if "tls" in survey_root.find('survey').attrib['scanner']:
# For TLS surveys, create multipoint geometries with all points from within list of geometries.
geometry = QgsMultiPoint()
[geometry.addGeometry(geom[0]) for geom in feature]
new_feature.setGeometry(geometry)
else:
# For ULS and ALS surveys, create polyline geometry from all points in list of geometries.
new_feature.setGeometry(QgsGeometry.fromPolyline([geom[0] for geom in feature]))
# Add attributes to feature: [id, leg_number, z_value]
new_feature.setAttributes([id, feature[0][2], feature[0][1]])
pr.addFeatures([new_feature])
id += 1
# Add layer to QGIS.
QgsProject.instance().addMapLayer(vector_layer)
def lock_in_config(self):
"""Function that visually locks in the configuration of survey parameters for the user."""
# Reset error message and platform label.
self.scanner_config_error.setHidden(True)
self.platform_type_label.setHidden(True)
# If all parameters have a value, hide comboboxes and show labels with bold writing as same location.
if self.platform_selection.count() != 0 and self.scanner_selection.count() != 0 and self.scene_selection.count() != 0:
self.selected_platform.setText(
"**" + self.platform_selection.currentText() + "**")
self.selected_scanner.setText(
"**" + self.scanner_selection.currentText() + "**")
self.selected_scene.setText("**" + self.scene_selection.currentText() + "**")
self.platform_selection.setHidden(True)
self.selected_platform.setHidden(False)
self.scanner_selection.setHidden(True)
self.selected_scanner.setHidden(False)
self.scene_selection.setHidden(True)
self.selected_scene.setHidden(False)
if self.platforms[self.platform_selection.currentText()][1] == 'groundvehicle':
self.altitude_widget.hide()
self.uls_widget.hide()
self.platform_type = 'groundvehicle'
self.platform_type_label.setText('**[MLS Survey]**')
self.platform_type_label.setHidden(False)
elif self.platforms[self.platform_selection.currentText()][1] == 'linearpath':
self.altitude_widget.show()
self.uls_widget.hide()
self.platform_type = 'linearpath'
self.platform_type_label.setText('**[Linearpath Survey]**')
self.platform_type_label.setHidden(False)
elif self.platforms[self.platform_selection.currentText()][1] == 'multicopter':
self.uls_widget.show()
self.altitude_widget.show()
self.platform_type = 'multicopter'
self.platform_type_label.setText('**[Multicopter Survey]**')
self.platform_type_label.setHidden(False)
else:
# If one of the parameters has not been selected, display error message.
self.scanner_config_error.setHidden(False)
def next_tab(self):
"""Function that moves TabWidget to next tab."""
self.tabWidget.setCurrentIndex(self.tabWidget.currentIndex()+1)
def prev_tab(self):
"""Function that moves TabWidget to previous tab."""
self.tabWidget.setCurrentIndex(self.tabWidget.currentIndex() - 1)
def parse_platform(self):
"""Take platform XML and add each platform option to combobox for user selection."""
# Reset error messages.
self.plat_xml_error.setHidden(True)
self.plat_xml_error.setText('<span style="color:red"> * Invalid Platform XML</span>')
# Clear combo box.
self.platform_selection.clear()
# Change locked in field back to combobox. Only necessary when user has previously locked in a platform.
self.selected_platform.setHidden(True)
self.platform_selection.setHidden(False)
try:
# Parse XML and extract options for platform:
platform_root = ET.parse(self.platform_input.filePath()).getroot()
for platform in platform_root.findall('platform'):
# Add name of each option to combobox.
self.platform_selection.addItem(platform.attrib['name'])
self.platforms[platform.attrib['name']] = [platform.attrib['id'], platform.attrib['type']]
if self.platform_selection.count() == 0:
# Give error message if no platform options are found.
self.plat_xml_error.setText('<span style="color:red"> * No valid platforms found</span>')
self.plat_xml_error.setHidden(False)
except Exception as err:
# If error occurs during above steps, stop function and give error message.
self.plat_xml_error.setHidden(False)
print(err)
return 0
def parse_scanner(self):
# Reset error messages.
self.scan_xml_error.setHidden(True)
self.scan_xml_error.setText('<span style="color:red"> * Invalid Scanner XML</span>')
# Clear combo box.
self.scanner_selection.clear()
# Change locked in field back to combobox. Only necessary when user has previously locked in a scanner.
self.selected_scanner.setHidden(True)
self.scanner_selection.setHidden(False)
try:
# Parse XML and extract options for scanners:
scanner_root = ET.parse(self.scanner_input.filePath()).getroot()
for scanner in scanner_root.findall('scanner'):
# Add name of each option to combobox.
self.scanner_selection.addItem(scanner.attrib['name'])
self.scanners[scanner.attrib['name']] = scanner.attrib['id']
if self.scanner_selection.count() == 0:
# Give error message if no scanner options are found.
self.scan_xml_error.setText('<span style="color:red"> * No valid scanners found</span>')
self.scan_xml_error.setHidden(False)
except Exception as err:
self.scan_xml_error.setHidden(False)
print(err)
return 0
def parse_scene(self):
# Reset error messages.
self.scene_xml_error.setHidden(True)
self.scene_xml_error.setText('<span style="color:red"> * Invalid Scene XML</span>')
# Clear combo box.
self.scene_selection.clear()
# Change locked in field back to combobox. Only necessary when user has previously locked in a scanner.
self.selected_scene.setHidden(True)
self.scene_selection.setHidden(False)
try:
# Parse XML and extract names of scenes:
scene_root = ET.parse(self.scene_input.filePath()).getroot()
for scene in scene_root.findall('scene'):
self.scene_selection.addItem(scene.attrib['name'])
self.scenes[scene.attrib['name']] = scene.attrib['id']
if self.scene_selection.count() == 0:
# Give error message if no scanner options are found.
self.scene_xml_error.setText('<span style="color:red"> * No valid scenes found</span>')
self.scene_xml_error.setHidden(False)
except Exception as err:
# If error occurs during above steps, stop function and give error message.
self.scene_xml_error.setHidden(False)
print(err)
return 0
def generate_survey(self):
"""Function that writes a HELIOS survey file based on user input from GUI"""
# Reset error messages.
self.layer_error_popup.setHidden(True)
self.survey_name_error_popup.setHidden(True)
self.output_dir_error_popup.setHidden(True)
self.plat_xml_error.setHidden(True)
self.scan_xml_error.setHidden(True)
self.scene_xml_error.setHidden(True)
self.final_msg.setHidden(True)
self.raster_layer_error.setHidden(True)
# Check for empty survey name and path input field.
# If empty, display error message(s) and stop function.
if self.survey_input.text() == "":
self.survey_name_error_popup.setHidden(False)
if self.survey_directory.filePath() == "":
self.output_dir_error_popup.setHidden(False)
return 0
# Check for empty output dir input field.
if self.survey_directory.filePath() == "":
self.output_dir_error_popup.setHidden(False)
return 0
# Create full survey filename with destination directory.
survey_destination = os.path.join(self.survey_directory.filePath(), self.survey_input.text() + ".xml")
# Get data from vector layer. Raises error if no vector layer was selected.
layer = self.layerBox.currentLayer()
try:
geom_type = layer.geometryType()
except Exception as err:
print(err)
self.layer_error_popup.setHidden(False)
return 0
else:
print(geom_type)
# TODO: What should happen when file already exists?
# At the moment is checked with dialogue.
# File creation. Error thrown if file already exists.
try:
survey_file = open(survey_destination, "x")
survey_file.close()
except Exception as err:
# Error box is opened and user input is saved to variable.
# Decision whether to continue and overwrite, or exit (returning 0).
continue_check = warning_box("Survey Overwrite Warning", "",
"This survey file already exists! Do you want to overwrite it?")
if not continue_check:
return 0
# Continues if file did not already exist or user decides to overwrite existing file.
survey_file = open(survey_destination, "w")
# File header with user input. Input is taken from labels showing current configuration.
survey_file.write('<?xml version="1.0"?>\n')
survey_file.write('<document>\n')
try:
# Error will occur here if no scanner config was selected.
survey_file.write(' <survey name="{survey}" platform="{platform}" scanner="{scanner}" scene="{scene}">\n'
.format(survey=self.survey_input.text(), platform=self.platform_input.filePath() + '#' + self.platforms[self.platform_selection.currentText()][0],
scanner=self.scanner_input.filePath() + '#' + self.scanners[self.scanner_selection.currentText()],
scene=self.scene_input.filePath() + '#' + self.scenes[self.scene_selection.currentText()]))
except IndexError:
# In case one of the scanner config fields is empty:
self.scanner_config_error.setHidden(False)
survey_file.close()
os.delete(survey_destination)
self.tabWidget.setCurrentIndex(self.tabWidget.currentIndex() - 1)
return 0
except Exception as err:
# Other errors:
print(err)
survey_file.close()
os.delete(survey_destination)
return 0
raster_given = False
gnd_raster = self.gnd_raster.currentLayer()
if gnd_raster != None:
if not isinstance(gnd_raster, QgsRasterLayer):
self.raster_layer_error.setHidden(False)
self.prev_tab()
return
raster_given = True
vector_crs = layer.crs()
raster_crs = gnd_raster.crs()
transform_context = QgsProject.instance().transformContext()
crs_transform = QgsCoordinateTransform(vector_crs, raster_crs, transform_context)
# Get vertices from features.
features = layer.getFeatures()
all_points = []
for feature_count, feature in enumerate(features):
geom = feature.geometry()
for v in geom.vertices():
if raster_given:
if isinstance(v, QgsPoint):
v_xy = QgsPointXY(v)
v_tranformed = crs_transform.transform(v_xy)
# For last vertice, set 'active' flag to false.
if v != [vert for vert in geom.vertices()][-1]:
all_points.append([v_tranformed.x(), v_tranformed.y(), float(self.flight_z.text()), "true", feature_count])
else:
all_points.append([v_tranformed.x(), v_tranformed.y(), float(self.flight_z.text()), "false", feature_count])
else:
# If on ground is checked, set altitude to 0 for all legs.
if self.platform_type == 'groundvehicle':
# For last vertice, set 'active' flag to false.
if v != [vert for vert in geom.vertices()][-1]:
all_points.append([v.x(), v.y(), 0, "true", feature_count])
else:
all_points.append([v.x(), v.y(), 0, "false", feature_count])
# If on ground isn't checked, set altitude to value entered by user.
else:
# For last vertice, set 'active' flag to false.
if v != [vert for vert in geom.vertices()][-1]:
all_points.append([v.x(), v.y(), float(self.flight_z.text()), "true", feature_count])
else:
all_points.append([v.x(), v.y(), float(self.flight_z.text()), "false", feature_count])
all_points_corrected = []
# Write survey legs. Only if raster is given.
if raster_given:
self.flight_alt = float(self.flight_z.text())
for i in range(len(all_points)):
if float(gnd_raster.dataProvider().sample(QgsPointXY(all_points[i][0], all_points[i][1]), 1)[1]) == False:
QgsMessageLog.logMessage("WARNING: Raster at point x={}, y={} returns z value nan. This entire geometry "
"will not be checked for altitude..".format(all_points[i][0], all_points[i][1]))
continue
# Only if leg is active..:
if all_points[i][3]=="true":
print('Trajectory active')
# Add raster height to flight alt at beginning of trajectory.
all_points[i][2] += float(gnd_raster.dataProvider().sample(QgsPointXY(all_points[i][0], all_points[i][1]), 1)[0])
# Add point entry to list with new corrected altitude values.
all_points_corrected.append([all_points[i][0], all_points[i][1], all_points[i][2], all_points[i][3], all_points[i][4]])
# For every leg, check for altitude 100 times.
frequency = 100
current_loc = all_points[i]
current_alt = all_points[i][2]
# Distance to be moved between each altitude check.
move_per_step = [(all_points[i+1][0]-all_points[i][0])/frequency, (all_points[i+1][1]-all_points[i][1])/frequency]
print('{}-{}/{}={}'.format(all_points[i][0], all_points[i+1][0], frequency, move_per_step[0]))
print('{}-{}/{}={}'.format(all_points[i][1], all_points[i+1][1], frequency, move_per_step[1]))
# Perform altitude checks, update altitude value if necessary.
for j in range(frequency):
current_gnd_z = gnd_raster.dataProvider().sample(QgsPointXY(current_loc[0], current_loc[1]), 1)[0]
distance_to_optimal = current_gnd_z+self.flight_alt-current_alt
if abs(distance_to_optimal)>float(self.flight_alt_range.text()):
# If altitude is out of range:
print('new alt: {}'.format(current_gnd_z+self.flight_alt))
# Update value in survey leg.
all_points_corrected.append([current_loc[0], current_loc[1], current_gnd_z+self.flight_alt, "true", all_points[i][4]])
# Update value for upcoming checks.
current_alt = current_gnd_z+self.flight_alt
# Move to next checkpoint.
current_loc[0] += move_per_step[0]
current_loc[1] += move_per_step[1]
# If leg is not active, fill in current altitude and move on to next leg.
if all_points[i][3] == "false":
print('Trajectory not active')
all_points_corrected.append([all_points[i][0], all_points[i][1], current_alt, "false", all_points[i][4]])
# No raster is given, skip altitude correction...:
else:
all_points_corrected = all_points
# Write legs to file.
for point in all_points_corrected:
if self.stripid_flag.isChecked():
survey_file.write(' <leg stripId="{}">\n'.format(point[4]))
else:
survey_file.write(' <leg>\n')
if self.platform_type != 'multicopter':
survey_file.write(' <platformSettings x="{x}" y="{y}" z="{z}" onGround="{gnd_flag}" '
'movePerSec_m="{v}"/>\n'.format(x=point[0], y=point[1], z=point[2],
gnd_flag="true" if self.platform_type=='groundvehicle' else "true" if self.on_ground.isChecked() else "false",
v=self.flight_v.text()))
else:
survey_file.write(' <platformSettings x="{x}" y="{y}" z="{z}" onGround="{gnd_flag}" '
'movePerSec_m="{v}" {smooth_turn} {stop_and_turn} {slowdown_enabled}/>\n'.format(x=point[0], y=point[1], z=point[2], gnd_flag="false",
v=self.flight_v.text(), smooth_turn="{}".format('smoothTurn="true"') if self.smooth_turn.isChecked() else "",
stop_and_turn="{}".format('stopAndTurn="true"') if self.stop_turn.isChecked() else "",
slowdown_enabled="{}".format('slowdownEnabled="false"') if self.slowdown_flag.isChecked() else ""))
survey_file.write(' <scannerSettings active="{active_flag}" pulseFreq_hz="{pulse_freq}" scanAngle_deg="{scan_angle}" '
'scanFreq_hz="{scan_freq}" headRotatePerSec_deg="0.0" headRotateStart_deg="0.0" '
'headRotateStop_deg="0.0" trajectoryTimeInterval_s="0.067"/>\n'.format(active_flag=point[3],
pulse_freq=self.pulse_freq.text(),
scan_angle=self.scan_angle.text(),
scan_freq=self.scan_freq.text()))
survey_file.write(' </leg>\n')
survey_file.write(' </survey>\n</document>')
survey_file.close()
# Display message for successful survey creation for user.
encoded_path = bytearray(QUrl.fromLocalFile(survey_destination).toEncoded()).decode()
self.final_msg.setText('Survey file successfully created: <a href="{}">{}</a>'.format(
encoded_path, survey_destination))
self.final_msg.setHidden(False)
# Set survey execution path to path of newly created survey.
self.survey_exec_path.setFilePath(survey_destination)
def closeEvent(self, event):
"""Function that closes the plugin."""
self.closingPlugin.emit()
event.accept()
def start_sim_worker(self):
"""Function that runs the HELIOS++ simulation."""
# Reset error messages.
self.sim_status.setHidden(True)
self.sim_final_output.setHidden(True)
self.survey_path_error.setHidden(True)
# Check for empty survey file field.
if self.survey_exec_path.filePath() == '':
self.survey_path_error.setHidden(False)
return 0
self.previous_path = os.getcwd()
os.chdir(self.helios_dir)
# Add helios path to python path.
if not self.helios_dir in sys.path:
sys.path.append(self.helios_dir)
# Create instance of worker that runs sim on another thread.
self.worker = Worker(self.helios_dir, self.survey_exec_path.filePath())
# New thread, move worker to thread.
self.thread = QThread(self)
self.worker.moveToThread(self.thread)
# Connect worker signals to main window functions.
self.worker.finished.connect(self.worker_finished)
self.worker.error.connect(self.worker_error)
#self.worker.progress.connect(self.sim_progress.setValue)
self.worker.progress.connect(self.set_runtime)
self.thread.started.connect(self.worker.run)
self.sim_cancel.clicked.connect(self.kill_worker)
# Start worker
self.thread.start()
# User status update
self.time_counter.setText('Time elapsed: 0 minute(s) and 0 second(s).')
self.sim_status.setHidden(False)
self.time_counter.setHidden(False)
def set_runtime(self, runtime):
self.time_counter.setText('Time elapsed: {} minute(s) and {} second(s).'.format(int(runtime)//60, int(runtime)%60))
def worker_finished(self, ret):
"""Function that runs once simulation has finished."""
# Clean up worker and thread.
self.worker.deleteLater()
self.thread.quit()
self.thread.wait()
self.thread.deleteLater()
# Hide sim status and sim counter
self.sim_status.setHidden(True)
self.time_counter.setHidden(True)
if ret==0:
# Worker has terminated without issues.
# Get survey name for final output dir
survey_root = ET.parse(self.survey_exec_path.filePath()).getroot()
survey_name = survey_root.find('survey').attrib['name']
# Find survey output directory (to inform the user).
output_dir = os.path.join(self.helios_dir, "output/Survey Playback/", survey_name)
# Find latest folder in survey output directory
all_survey_outputs = [os.path.join(output_dir, d) for d in os.listdir(output_dir) if
os.path.isdir(os.path.join(output_dir, d))]
latest_survey_output = os.path.join(max(all_survey_outputs, key=os.path.getmtime), 'points/')
# Load output point cloud into QGIS if corresponding box was checked.
if self.load_output_check.isChecked():
# Iterate over output files and load all .las files into qgis
for filename in os.listdir(latest_survey_output):
if filename.endswith(".las"):
iface.addPointCloudLayer(os.path.join(latest_survey_output, filename),
survey_name + '-' + os.path.basename(filename).split('.')[0],
"pdal")
# Report the result and output dir to user.
encoded_path = bytearray(
QUrl.fromLocalFile(latest_survey_output).toEncoded()).decode()
self.sim_final_output.setText('Simulation complete. Output is located at: <a href="{}">{}</a>'
.format(encoded_path, latest_survey_output))
self.sim_final_output.setHidden(False)
elif ret == 2:
print('Simulation cancelled.')
else:
# Notify the user that something went wrong.
print('Something went wrong! See the message log for more information.')
# Change back to original path.
os.chdir(self.previous_path)
def data_gen_worker_finished(self, ret):
# Clean up worker and thread.
self.worker.deleteLater()
self.thread.quit()
self.thread.wait()
self.thread.deleteLater()
if ret==0:
pass
elif ret==2:
print('Process cancelled.')
else:
# Notify the user that something went wrong.
print('Something went wrong! See the message log for more information.')
def worker_error(self, e, exception_string):
"""Runs when worker throws an error."""
QgsMessageLog.logMessage('Worker thread raised an exception: \n{}\n'.format(exception_string))
# Change back to original path.
os.chdir(self.previous_path)
def kill_worker(self):
"""Runs workers kill funciton."""
self.worker.kill()
def data_gen_configuration(self):
self.config_window = DataGenConfig(self)
if self.config_window.exec() == 0:
pass
def refresh_trajectory(self):
self.trajectories = [l for l in QgsProject.instance().mapLayers().values() if l.type() == QgsVectorLayer.VectorLayer]
for trajectory in self.trajectories:
self.trajectory_box.addItem(trajectory.name())
def generate_data(self):
import random
self.data_gen_status.setHidden(True)
self.previous_path = os.getcwd()
os.chdir(self.helios_dir)
# Add helios path to python path.
if not self.helios_dir in sys.path:
sys.path.append(self.helios_dir)
for sim_count in range(1, int(self.config_window.num_iterations.text())+1):
survey_file_name = '{}{}.xml'.format(self.data_gen_name.text(), sim_count) # i
self.data_gen_status.setText('Generating Survey no. {}: {}'.format(sim_count, os.path.join(os.getcwd(), survey_file_name)))
self.data_gen_status.setHidden(False)
scene = self.config_window.scene_selection_2.currentText()
scene = self.config_window.config_scene_input.filePath() + '#' + self.config_window.config_scenes[scene]
scanner = random.choice(self.config_window.scanner_selection_2.checkedItems())
scanner_path = self.config_window.config_scanner_input.filePath() + '#' + self.config_window.config_scanners[scanner][0]
# Generate random survey parameters.
platform = "data/platforms.xml#sr22"
speed = random.randint(int(self.config_window.min_speed.text()), int(self.config_window.max_speed.text())) # in m/s - roughly estimated from point cloud
altitude = random.randint(int(self.config_window.min_altitude.text()), int(self.config_window.max_altitude.text()))
pulse_freq = int(random.choice(self.config_window.config_scanners[scanner][1]))
scan_freq = random.randint(int(self.config_window.config_scanners[scanner][3]) + 15, int(self.config_window.config_scanners[scanner][4]))
scan_angle = random.randint(5, int(float(self.config_window.config_scanners[scanner][2])))
survey_name = survey_file_name.split('.')[0]
survey_file = open(survey_file_name, "w")
survey_file.write('<?xml version="1.0"?>\n')
survey_file.write('<document>\n')
survey_file.write(' <survey name="{survey}" platform="{platform}" scanner="{scanner}" scene="{scene}">\n'
.format(survey=survey_name, platform=platform, scanner=scanner_path, scene=scene))
layer = random.choice(self.trajectory_box.checkedItems())
layer = QgsProject.instance().mapLayersByName(layer)[0]
gnd_raster = self.config_window.raster.currentLayer()
raster_given=False
if gnd_raster != None:
raster_given = True
vector_crs = layer.crs()
raster_crs = gnd_raster.crs()
transform_context = QgsProject.instance().transformContext()
crs_transform = QgsCoordinateTransform(vector_crs, raster_crs, transform_context)
# Get vertices from features.
features = layer.getFeatures()
all_points = []
for feature_count, feature in enumerate(features):
geom = feature.geometry()
for v in geom.vertices():
if raster_given:
if isinstance(v, QgsPoint):
v_xy = QgsPointXY(v)
v_tranformed = crs_transform.transform(v_xy)
# For last vertice, set 'active' flag to false.
if v != [vert for vert in geom.vertices()][-1]:
all_points.append(
[v_tranformed.x(), v_tranformed.y(), float(altitude), "true",
feature_count])
else:
all_points.append(
[v_tranformed.x(), v_tranformed.y(), float(altitude), "false",
feature_count])
else:
# If on ground is checked, set altitude to 0 for all legs.
if self.platform_type == 'groundvehicle':
# For last vertice, set 'active' flag to false.
if v != [vert for vert in geom.vertices()][-1]:
all_points.append([v.x(), v.y(), 0, "true", feature_count])
else:
all_points.append([v.x(), v.y(), 0, "false", feature_count])
# If on ground isn't checked, set altitude to value entered by user.
else:
# For last vertice, set 'active' flag to false.
if v != [vert for vert in geom.vertices()][-1]:
all_points.append(
[v.x(), v.y(), float(self.flight_z.text()), "true", feature_count])
else:
all_points.append(
[v.x(), v.y(), float(self.flight_z.text()), "false", feature_count])
all_points_corrected = []
# Write survey legs. Only if raster is given.
if raster_given:
self.flight_alt = float(altitude)
for i in range(len(all_points)):
if float(gnd_raster.dataProvider().sample(QgsPointXY(all_points[i][0], all_points[i][1]), 1)[
1]) == False:
QgsMessageLog.logMessage(
"WARNING: Raster at point x={}, y={} returns z value nan. This entire geometry "
"will not be checked for altitude..".format(all_points[i][0], all_points[i][1]))
continue
# Only if leg is active..:
if all_points[i][3] == "true":