-
Notifications
You must be signed in to change notification settings - Fork 0
/
udef_arp_qgis.py
3118 lines (2614 loc) · 139 KB
/
udef_arp_qgis.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 -*-
"""
/***************************************************************************
UDef-ARP Plugin for QGIS
A modified version of the UDef-ARP repository [https://github.com/ClarkCGA/UDef-ARP]
that enables the tool to be fully integrated into QGIS as a plugin
Created using the Plugin Builder: http://g-sherman.github.io/Qgis-Plugin-Builder/
-------------------
begin : 2024-04-01
copyright : (C) 2024 by Eli Simonson
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. *
* *
***************************************************************************/
"""
# Import libraries
import sys
import os
import os.path
from pathlib import Path, PureWindowsPath
from osgeo import gdal
import numpy as np
# QGIS imports
from qgis.core import (
QgsMessageLog, QgsProject, Qgis, QgsMapLayerProxyModel,
QgsRasterLayer, QgsVectorLayer
)
from qgis.PyQt.QtCore import (
QSettings, QTranslator, QCoreApplication, QUrl, Qt
)
from qgis.PyQt.QtGui import (
QFontDatabase, QIcon, QFont, QDesktopServices, QColor
)
from qgis.PyQt.QtWidgets import (
QAction, QFileDialog, QApplication, QWidget, QProgressDialog, QMessageBox
)
from qgis.PyQt import uic, QtWidgets
from qgis.gui import QgsMapLayerComboBox
# Custom imports
from .resources import *
from .allocation_tool import AllocationTool
from .vulnerability_map import VulnerabilityMap
from .model_evaluation import ModelEvaluation
# GDAL exceptions
gdal.UseExceptions()
# This loads your .ui file so that PyQt can populate your plugin with the elements from Qt Designer
FORM_CLASS0, _ = uic.loadUiType(os.path.join(os.path.dirname(__file__), 'data\\intro_screen.ui'))
FORM_CLASS1, _ = uic.loadUiType(os.path.join(os.path.dirname(__file__), 'data\\rmt_fit_cal_screen_Dev.ui'))
FORM_CLASS2, _ = uic.loadUiType(os.path.join(os.path.dirname(__file__), 'data\\at_fit_cal_screen_Dev.ui'))
FORM_CLASS3, _ = uic.loadUiType(os.path.join(os.path.dirname(__file__), 'data\\mct_fit_cal_screen_Dev.ui'))
FORM_CLASS4, _ = uic.loadUiType(os.path.join(os.path.dirname(__file__), 'data\\rmt_pre_cnf_screen_Dev.ui'))
FORM_CLASS5, _ = uic.loadUiType(os.path.join(os.path.dirname(__file__), 'data\\at_pre_cnf_screen_Dev.ui'))
FORM_CLASS6, _ = uic.loadUiType(os.path.join(os.path.dirname(__file__), 'data\\mct_pre_cnf_screen_Dev.ui'))
FORM_CLASS7, _ = uic.loadUiType(os.path.join(os.path.dirname(__file__), 'data\\rmt_fit_hrp_screen_Dev.ui'))
FORM_CLASS8, _ = uic.loadUiType(os.path.join(os.path.dirname(__file__), 'data\\at_fit_hrp_screen_Dev.ui'))
FORM_CLASS9, _ = uic.loadUiType(os.path.join(os.path.dirname(__file__), 'data\\rmt_pre_vp_screen_Dev.ui'))
FORM_CLASS10, _ = uic.loadUiType(os.path.join(os.path.dirname(__file__), 'data\\at_pre_vp_screen_Dev.ui'))
# Define the style sheet for the combo box
style_sheet = """
/* Set text color to black */
color: black;
/* Set background color to white and border color to black */
background-color: white;
border: 1px solid #c0c0c0; /* light grey border color */
/* Set hover color to blue */
selection-background-color: #add8e6;
"""
######################################################################################################
class IntroScreen(QtWidgets.QDialog, FORM_CLASS0):
def __init__(self, parent=None):
"""Constructor."""
super(IntroScreen, self).__init__(parent)
# Set up the user interface from Designer through FORM_CLASS0.
self.setupUi(self)
# Connect functions to the UI
self.connect_signals()
def connect_signals(self):
self.Fit_Cal_button.clicked.connect(self.gotofitcal)
self.Pre_Cnf_button.clicked.connect(self.gotoprecnf)
self.Fit_Hrp_button.clicked.connect(self.gotofithrp)
self.Pre_VP_button.clicked.connect(self.gotoprevp)
self.doc_button.clicked.connect(self.openDocument)
def gotofitcal(self):
rmt_fit_cal = RMT_FIT_CAL_SCREEN()
stacked_widget.addWidget(rmt_fit_cal)
stacked_widget.setCurrentIndex(stacked_widget.currentIndex() + 1)
def gotoprecnf(self):
rmt_pre_cnf = RMT_PRE_CNF_SCREEN()
stacked_widget.addWidget(rmt_pre_cnf)
stacked_widget.setCurrentIndex(stacked_widget.currentIndex() + 1)
def gotofithrp(self):
rmt_fit_hrp = RMT_FIT_HRP_SCREEN()
stacked_widget.addWidget(rmt_fit_hrp)
stacked_widget.setCurrentIndex(stacked_widget.currentIndex() + 1)
def gotoprevp(self):
rmt_pre_vp = RMT_PRE_VP_SCREEN()
stacked_widget.addWidget(rmt_pre_vp)
stacked_widget.setCurrentIndex(stacked_widget.currentIndex() + 1)
def openDocument(self):
pdf_path = os.path.join(os.path.dirname(__file__), 'doc\\UDef-ARP_Introduction.pdf')
QDesktopServices.openUrl(QUrl.fromLocalFile(str(pdf_path)))
######################################################################################################
class RMT_FIT_CAL_SCREEN(QtWidgets.QDialog, FORM_CLASS1):
def __init__(self, parent=None):
"""Constructor."""
super(RMT_FIT_CAL_SCREEN, self).__init__(parent)
# Store the initial directory path
self.initial_directory = os.getcwd()
# Set up the user interface from Designer through FORM_CLASS1.
self.setupUi(self)
# Workspace handling
if central_data_store.directory is not None and self.folder_entry is not None:
self.directory = central_data_store.directory
self.folder_entry.setText(str(central_data_store.directory))
if central_data_store.directory is not None and self.folder_entry_2 is not None:
self.directory_2 = central_data_store.directory
self.folder_entry_2.setText(str(central_data_store.directory))
self.AT_button2.clicked.connect(self.gotoat2)
self.Intro_button2.clicked.connect(self.gotointro2)
self.MCT_button2.clicked.connect(self.gotomct2)
# Tab 1 Widgets
self.doc_button = self.tab1.findChild(QWidget, "doc_button")
self.select_folder_button = self.tab1.findChild(QWidget, "select_folder_button")
self.deforestation_hrp_button = self.tab1.findChild(QWidget, "deforestation_hrp_button")
self.mask_button = self.tab1.findChild(QWidget, "mask_button")
self.fd_button = self.tab1.findChild(QWidget, "fd_button")
self.calculate_button2 = self.tab1.findChild(QWidget, "calculate_button2")
self.ok_button2 = self.tab1.findChild(QWidget, "ok_button2")
# Tab 2 Widgets
self.doc_button_2 = self.tab2.findChild(QWidget, "doc_button_2")
self.select_folder_button_2 = self.tab2.findChild(QWidget, "select_folder_button_2")
self.mask_button_2 = self.tab2.findChild(QWidget, "mask_button_2")
self.fmask_button_2 = self.tab2.findChild(QWidget, "fmask_button_2")
self.fd_button_2 = self.tab2.findChild(QWidget, "fd_button_2")
self.ok_button2_2 = self.tab2.findChild(QWidget, "ok_button2_2")
# Connect Tab 1 Widgets to Functions
self.doc_button.clicked.connect(self.openDocument)
self.select_folder_button.clicked.connect(self.select_working_directory)
self.deforestation_hrp_button.clicked.connect(lambda: self.selectRaster(self.deforestation_hrp_entry, 'Map of Deforestation in the HRP'))
self.mask_button.clicked.connect(lambda: self.selectRaster(self.mask_entry, 'Mask of Study Area'))
self.fd_button.clicked.connect(lambda: self.selectRaster(self.comboBox, 'Map of Distance from the Forest Edge in CAL'))
self.calculate_button2.clicked.connect(self.process_data2_nrt)
self.ok_button2.clicked.connect(self.process_data2)
# Connect Tab 2 Widgets to Functions
self.doc_button_2.clicked.connect(self.openDocument_2)
self.select_folder_button_2.clicked.connect(self.select_working_directory_2)
self.mask_button_2.clicked.connect(lambda: self.selectRaster(self.mask_entry_2, 'Mask of Study Area'))
self.fmask_button_2.clicked.connect(lambda: self.selectRaster(self.fmask_entry_2, 'Mask of Forest Area'))
self.fd_button_2.clicked.connect(lambda: self.selectRaster(self.in_fn_entry_2, 'Map of Empirical transition potential for CAL'))
self.ok_button2_2.clicked.connect(self.process_data2_2)
# Create Class Attributes
self.vulnerability_map = VulnerabilityMap()
self.vulnerability_map.progress_updated.connect(self.update_progress)
self.directory = None
self.in_fn = None
self.deforestation_hrp = None
self.mask = None
self.NRT = None
if central_data_store.NRT is not None:
self.nrt_entry.setText(str(central_data_store.NRT))
self.n_classes = None
self.out_fn = None
self.out_fn_entry.setPlaceholderText('e.g., Acre_Vulnerability_CAL.tif')
self.directory_2 = None
self.mask_2 = None
self.fmask_2 = None
self.in_fn_2 = None
self.out_fn_2 = None
self.n_classes_2 = None
self.out_fn_entry_2.setPlaceholderText('e.g., Acre_Vulnerability_CAL.tif')
# Provide intitial settings for each comboBox
#self.tabWidget.setStyleSheet("QTabWidget::pane { border: 1px solid white; }");
self.comboBox.setStyleSheet(style_sheet)
self.deforestation_hrp_entry.setStyleSheet(style_sheet)
self.mask_entry.setStyleSheet(style_sheet)
self.mask_entry_2.setStyleSheet(style_sheet)
self.fmask_entry_2.setStyleSheet(style_sheet)
self.in_fn_entry_2.setStyleSheet(style_sheet)
self.comboBox.setCurrentIndex(-1)
self.deforestation_hrp_entry.setCurrentIndex(-1)
self.mask_entry.setCurrentIndex(-1)
self.mask_entry_2.setCurrentIndex(-1)
self.fmask_entry_2.setCurrentIndex(-1)
self.in_fn_entry_2.setCurrentIndex(-1)
self.comboBox.setFilters(QgsMapLayerProxyModel.RasterLayer)
self.deforestation_hrp_entry.setFilters(QgsMapLayerProxyModel.RasterLayer)
self.mask_entry.setFilters(QgsMapLayerProxyModel.RasterLayer)
self.mask_entry_2.setFilters(QgsMapLayerProxyModel.RasterLayer)
self.fmask_entry_2.setFilters(QgsMapLayerProxyModel.RasterLayer)
self.in_fn_entry_2.setFilters(QgsMapLayerProxyModel.RasterLayer)
def gotoat2(self):
os.chdir(self.initial_directory)
at2 = AT_FIT_CAL_SCREEN()
stacked_widget.addWidget(at2)
stacked_widget.setCurrentIndex(stacked_widget.currentIndex() + 1)
def gotomct2(self):
os.chdir(self.initial_directory)
mct2 = MCT_FIT_CAL_SCREEN()
stacked_widget.addWidget(mct2)
stacked_widget.setCurrentIndex(stacked_widget.currentIndex() + 1)
def gotointro2(self):
os.chdir(self.initial_directory)
intro2 = IntroScreen()
stacked_widget.addWidget(intro2)
stacked_widget.setCurrentIndex(stacked_widget.currentIndex() + 1)
def openDocument(self):
pdf_path = os.path.join(os.path.dirname(__file__), "doc\\TestFitVM.pdf")
QDesktopServices.openUrl(QUrl.fromLocalFile(str(pdf_path)))
def openDocument_2(self):
pdf_path = os.path.join(os.path.dirname(__file__), "doc\\TestFitVM.pdf")
QDesktopServices.openUrl(QUrl.fromLocalFile(str(pdf_path)))
def select_working_directory(self):
data_folder = QFileDialog.getExistingDirectory(self, "Working Directory")
data_folder_path = Path(data_folder)
self.directory = str(data_folder_path)
self.folder_entry.setText(self.directory)
self.folder_entry_2.setText(self.directory)
central_data_store.directory = self.directory
def selectRaster(self, comboBox, string):
"""
Opening the raster layer file and adding the path to the combobox
on end of the list with comboBox items.
:param comboBox: Qt combobox.
:type comboBox: QComboBox
"""
rast_path = QFileDialog.getOpenFileName(self, string)
index = comboBox.currentIndex()
comboBox.setAdditionalItems([rast_path[0]])
ind = comboBox.count() - 1
comboBox.setCurrentIndex(ind)
def select_working_directory_2(self):
data_folder_2 = QFileDialog.getExistingDirectory(self, "Working Directory")
data_folder_path_2 = Path(data_folder_2)
self.directory_2 = str(data_folder_path_2)
self.folder_entry_2.setText(self.directory_2)
self.folder_entry.setText(self.directory_2)
central_data_store.directory = self.directory_2
def process_data2_nrt(self):
try:
self.in_fn = self.comboBox.currentLayer().source()
except Exception:
self.in_fn = self.comboBox.currentText()
try:
self.deforestation_hrp = self.deforestation_hrp_entry.currentLayer().source()
except Exception:
self.deforestation_hrp = self.deforestation_hrp_entry.currentText()
try:
self.mask = self.mask_entry.currentLayer().source()
except Exception:
self.mask = self.mask_entry.currentText()
images = [self.in_fn, self.deforestation_hrp, self.mask]
# Check if all images have the same resolution
resolutions = [map_checker.get_image_resolution(img) for img in images]
if len(set(resolutions)) != 1:
QMessageBox.critical(None, "Error", "All the input raster images must have the same spatial resolution!")
return
directory = self.folder_entry.text()
# Check if all images have the same number of rows and columns
dimensions = [map_checker.get_image_dimensions(img) for img in images]
if len(set(dimensions)) != 1:
QMessageBox.critical(None, "Error",
"All the input raster images must have the same number of rows and columns!")
return
if not self.in_fn or not self.deforestation_hrp or not self.mask:
QMessageBox.critical(self, "Error", "Please select all input files!")
return
if not map_checker.check_binary_map(self.deforestation_hrp):
QMessageBox.critical(None, "Error",
"'MAP OF DEFORESTATION IN THE HRP' must be a binary map (0 and 1) where the 1’s indicate deforestation.")
return
if not map_checker.check_binary_map(self.mask):
QMessageBox.critical(None, "Error",
"'MASK OF THE JURISDICTION' must be a binary map (0 and 1) where the 1’s indicate jurisdiction.")
return
# Show "Processing" message
processing_message = "Calculating NRT..."
self.progressDialog = QProgressDialog(processing_message, None, 0, 100, self)
# Change the font size
font = QFont()
font.setPointSize(9)
self.progressDialog.setFont(font)
self.progressDialog.setWindowTitle("Calculating")
self.progressDialog.setWindowModality(Qt.WindowModal)
self.progressDialog.setMinimumDuration(0)
self.progressDialog.resize(400, 300)
self.progressDialog.show()
QApplication.processEvents()
try:
self.vulnerability_map.set_working_directory(directory)
NRT = self.vulnerability_map.nrt_calculation(self.in_fn, self.deforestation_hrp, self.mask)
# Update the central data store
central_data_store.NRT = NRT
QMessageBox.information(self, "Processing Completed", f"Processing completed!\nNRT is: {NRT}")
self.nrt_entry.setText(str(NRT))
self.progressDialog.close()
except Exception as e:
self.progressDialog.close()
QMessageBox.critical(self, "Error", f"An error occurred during processing: {str(e)}")
def process_data2(self):
try:
self.in_fn = self.comboBox.currentLayer().source()
except Exception:
self.in_fn = self.comboBox.currentText()
if not self.in_fn:
QMessageBox.critical(self, "Error", "Please select the input file!")
return
NRT = self.nrt_entry.text()
if not NRT:
QMessageBox.critical(self, "Error", "Please enter the NRT value!")
return
try:
self.NRT = int(NRT)
if (self.NRT <= 0):
QMessageBox.critical(self, "Error", "NRT value should be larger than 0!")
return
except ValueError:
QMessageBox.critical(self, "Error", "NRT value should be a valid number!")
return
directory = self.folder_entry.text()
n_classes = int(29)
if not n_classes:
QMessageBox.critical(self, "Error", "Please enter the number of classes!")
return
try:
self.n_classes = int(n_classes)
if (self.n_classes <= 0):
QMessageBox.critical(self, "Error", "Number of classes should be larger than 0!")
return
except ValueError:
QMessageBox.critical(self, "Error", "Number of classes value should be a valid number!")
return
out_fn = self.out_fn_entry.text()
if not out_fn:
QMessageBox.critical(self, "Error", "Please enter the name of Vulnerability Map in CAL!")
return
# Check if the out_fn has the correct file extension
if not (out_fn.endswith('.tif') or out_fn.endswith('.rst')):
QMessageBox.critical(self, "Error",
"Please enter .rst or .tif extension in the name of Vulnerability Map in CAL!")
return
# Show "Processing" message
processing_message = "Processing data..."
self.progressDialog = QProgressDialog(processing_message, None, 0, 100, self)
# Change the font size
font = QFont()
font.setPointSize(9)
self.progressDialog.setFont(font)
self.progressDialog.setWindowTitle("Processing")
self.progressDialog.setWindowModality(Qt.WindowModal)
self.progressDialog.setMinimumDuration(0)
self.progressDialog.resize(400, 300)
self.progressDialog.show()
QApplication.processEvents()
try:
self.vulnerability_map.set_working_directory(directory)
mask_arr = self.vulnerability_map.geometric_classification(self.in_fn, NRT, n_classes)
self.vulnerability_map.array_to_image(self.in_fn, out_fn, mask_arr, gdal.GDT_Int16, -1)
self.vulnerability_map.replace_ref_system(self.in_fn, out_fn)
if self.checkBox.isChecked():
basename = os.path.splitext(os.path.basename(out_fn))[0]
layer = QgsRasterLayer(out_fn, basename)
layer.setDataSource(os.path.join(directory, out_fn), basename, 'gdal')
QgsProject.instance().addMapLayer(layer)
QMessageBox.information(self, "Processing Completed", "Processing completed!")
self.progressDialog.close()
except Exception as e:
self.progressDialog.close()
QMessageBox.critical(self, "Error", f"An error occurred during processing: {str(e)}")
def process_data2_2(self):
try:
self.in_fn_2 = self.in_fn_entry_2.currentLayer().source()
except Exception:
self.in_fn_2 = self.in_fn_entry_2.currentText()
try:
self.mask_2 = self.mask_entry_2.currentLayer().source()
except Exception:
self.mask_2 = self.mask_entry_2.currentText()
try:
self.fmask_2 = self.fmask_entry_2.currentLayer().source()
except Exception:
self.fmask_2 = self.fmask_entry_2.currentText()
images = [self.in_fn_2, self.mask_2, self.fmask_2]
# Check if all images have the same resolution
resolutions = [map_checker.get_image_resolution(img) for img in images]
if len(set(resolutions)) != 1:
QMessageBox.critical(None, "Error", "All the input raster images must have the same spatial resolution!")
return
# Check if all images have the same number of rows and columns
dimensions = [map_checker.get_image_dimensions(img) for img in images]
if len(set(dimensions)) != 1:
QMessageBox.critical(None, "Error",
"All the input raster images must have the same number of rows and columns!")
return
if not self.in_fn_2 or not self.mask_2 or not self.fmask_2:
QMessageBox.critical(self, "Error", "Please select the input file!")
return
n_classes_2 = int(30)
directory_2 = self.folder_entry_2.text()
out_fn_2 = self.out_fn_entry_2.text()
if not out_fn_2:
QMessageBox.critical(self, "Error", "Please enter the name of Vulnerability Map in CAL!")
return
# Check if the out_fn has the correct file extension
if not (out_fn_2.endswith('.tif') or out_fn_2.endswith('.rst')):
QMessageBox.critical(self, "Error",
"Please enter .rst or .tif extension in the name of Vulnerability Map in CAL!")
return
if not map_checker.check_binary_map(self.fmask_2):
QMessageBox.critical(None, "Error",
"'MASK OF FOREST AREAS IN THE CAL' must be a binary map (0 and 1) where the 1’s indicate forest areas.")
return
if not map_checker.check_binary_map(self.mask_2):
QMessageBox.critical(None, "Error",
"'MASK OF THE NON-EXCLUDED JURISDICTION' must be a binary map (0 and 1) where the 1’s indicate areas inside the jurisdiction.")
return
# Show "Processing" message
processing_message = "Processing data..."
self.progressDialog = QProgressDialog(processing_message, None, 0, 100, self)
# Change the font size
font = QFont()
font.setPointSize(9)
self.progressDialog.setFont(font)
self.progressDialog.setWindowTitle("Processing")
self.progressDialog.setWindowModality(Qt.WindowModal)
self.progressDialog.setMinimumDuration(0)
self.progressDialog.resize(400, 300)
self.progressDialog.show()
QApplication.processEvents()
try:
self.vulnerability_map.set_working_directory(directory_2)
mask_arr = self.vulnerability_map.geometric_classification_alternative(self.in_fn_2, n_classes_2, self.mask_2, self.fmask_2)
self.vulnerability_map.array_to_image(self.in_fn_2, out_fn_2, mask_arr, gdal.GDT_Int16, -1)
self.vulnerability_map.replace_ref_system(self.in_fn_2, out_fn_2)
if self.checkBox_2.isChecked():
basename = os.path.splitext(os.path.basename(out_fn_2))[0]
layer = QgsRasterLayer(out_fn_2, basename)
layer.setDataSource(os.path.join(directory_2, out_fn_2), basename, 'gdal')
QgsProject.instance().addMapLayer(layer)
QMessageBox.information(self, "Processing Completed", "Processing completed!")
self.progressDialog.close()
except Exception as e:
self.progressDialog.close()
QMessageBox.critical(self, "Error", f"An error occurred during processing: {str(e)}")
def update_progress(self, value):
# Update QProgressDialog with the new value
if self.progressDialog is not None:
self.progressDialog.setValue(value)
######################################################################################################
class AT_FIT_CAL_SCREEN(QtWidgets.QDialog, FORM_CLASS2):
def __init__(self, parent=None):
"""Constructor."""
super(AT_FIT_CAL_SCREEN, self).__init__(parent)
# Store the initial directory path
self.initial_directory = os.getcwd()
# Set up the user interface from Designer through FORM_CLASS2.
self.setupUi(self)
# Workspace handling
if central_data_store.directory is not None and self.folder_entry is not None:
self.directory = central_data_store.directory
self.folder_entry.setText(str(central_data_store.directory))
self.Intro_button3.clicked.connect(self.gotointro3)
self.RMT_button3.clicked.connect(self.gotormt3)
self.MCT_button3.clicked.connect(self.gotomct3)
self.doc_button.clicked.connect(self.openDocument)
self.select_folder_button.clicked.connect(self.select_working_directory)
self.municipality_button.clicked.connect(lambda: self.selectRaster(self.municipality_entry, 'Map of Administrative Divisions'))
self.risk30_hrp_button.clicked.connect(lambda: self.selectRaster(self.risk30_hrp_entry, 'Vulnerability Map in CAL'))
self.deforestation_hrp_button.clicked.connect(lambda: self.selectRaster(self.deforestation_hrp_entry, 'Map of Deforestation in the CAL'))
self.ok_button3.clicked.connect(self.process_data3)
self.allocation_tool = AllocationTool()
# Connect the progress_updated signal to the update_progress method
self.allocation_tool.progress_updated.connect(self.update_progress)
self.directory = None
self.risk30_hrp = None
self.municipality = None
self.deforestation_hrp = None
self.out_fn1 = None
self.out_fn2 = None
self.csv_name = None
self.image1_entry.setPlaceholderText('e.g., Acre_Modeling_Region_CAL.tif')
self.csv_entry.setPlaceholderText('e.g., Relative_Frequency_Table_CAL.csv')
self.image2_entry.setPlaceholderText('e.g., Acre_Fitted_Density_Map_CAL.tif')
self.setWindowTitle("JNR Integrated Risk/Allocation Tool")
# Provide intitial settings for each comboBox
self.municipality_entry.setStyleSheet(style_sheet)
self.deforestation_hrp_entry.setStyleSheet(style_sheet)
self.risk30_hrp_entry.setStyleSheet(style_sheet)
self.municipality_entry.setCurrentIndex(-1)
self.deforestation_hrp_entry.setCurrentIndex(-1)
self.risk30_hrp_entry.setCurrentIndex(-1)
self.municipality_entry.setFilters(QgsMapLayerProxyModel.RasterLayer)
self.deforestation_hrp_entry.setFilters(QgsMapLayerProxyModel.RasterLayer)
self.risk30_hrp_entry.setFilters(QgsMapLayerProxyModel.RasterLayer)
def gotormt3(self):
os.chdir(self.initial_directory)
rmt3 = RMT_FIT_CAL_SCREEN()
stacked_widget.addWidget(rmt3)
stacked_widget.setCurrentIndex(stacked_widget.currentIndex() + 1)
def gotointro3(self):
os.chdir(self.initial_directory)
intro3 = IntroScreen()
stacked_widget.addWidget(intro3)
stacked_widget.setCurrentIndex(stacked_widget.currentIndex() + 1)
def gotomct3(self):
os.chdir(self.initial_directory)
mct3 = MCT_FIT_CAL_SCREEN()
stacked_widget.addWidget(mct3)
stacked_widget.setCurrentIndex(stacked_widget.currentIndex() + 1)
def openDocument(self):
pdf_path = os.path.join(os.path.dirname(__file__), "doc\\TestFitAM.pdf")
QDesktopServices.openUrl(QUrl.fromLocalFile(str(pdf_path)))
def select_working_directory(self):
data_folder = QFileDialog.getExistingDirectory(self, "Working Directory")
data_folder_path = Path(data_folder)
self.directory = str(data_folder_path)
self.folder_entry.setText(self.directory)
central_data_store.directory = self.directory
def selectRaster(self, comboBox, string):
"""
Opening the raster layer file and adding the path to the combobox
on end of the list with comboBox items.
:param comboBox: Qt combobox.
:type comboBox: QComboBox
"""
rast_path = QFileDialog.getOpenFileName(self, string)
index = comboBox.currentIndex()
comboBox.setAdditionalItems([rast_path[0]])
ind = comboBox.count() - 1
comboBox.setCurrentIndex(ind)
def process_data3(self):
try:
self.risk30_hrp = self.risk30_hrp_entry.currentLayer().source()
except Exception:
self.risk30_hrp = self.risk30_hrp_entry.currentText()
try:
self.municipality = self.municipality_entry.currentLayer().source()
except Exception:
self.municipality = self.municipality_entry.currentText()
try:
self.deforestation_hrp = self.deforestation_hrp_entry.currentLayer().source()
except Exception:
self.deforestation_hrp = self.deforestation_hrp_entry.currentText()
images = [self.risk30_hrp, self.municipality, self.deforestation_hrp]
# Check if all images have the same resolution
resolutions = [map_checker.get_image_resolution(img) for img in images]
if len(set(resolutions)) != 1:
QMessageBox.critical(None, "Error", "All the input raster images must have the same spatial resolution!")
return
# Check if all images have the same number of rows and columns
dimensions = [map_checker.get_image_dimensions(img) for img in images]
if len(set(dimensions)) != 1:
QMessageBox.critical(None, "Error",
"All the input raster images must have the same number of rows and columns!")
return
if not self.risk30_hrp or not self.municipality or not self.deforestation_hrp:
QMessageBox.critical(self, "Error", "Please select all input files!")
return
directory = self.folder_entry.text()
out_fn1 = self.image1_entry.text()
if not out_fn1:
QMessageBox.critical(self, "Error", "Please enter the name for Modeling Region Map in CAL!")
return
if not (out_fn1.endswith('.tif') or out_fn1.endswith('.rst')):
QMessageBox.critical(self, "Error",
"Please enter .rst or .tif extension in the name for Modeling Region Map in CAL!")
return
csv_name = self.csv_entry.text()
if not csv_name:
QMessageBox.critical(self, "Error", "Please enter the name for the Relative Frequency Table!")
return
if not (csv_name.endswith('.csv')):
QMessageBox.critical(self, "Error",
"Please enter .csv extension in the name of Relative Frequency Table!")
return
out_fn2 = self.image2_entry.text()
if not out_fn2:
QMessageBox.critical(self, "Error", "Please enter the name for Fitted Density Map in the CAL!")
return
if not (out_fn2.endswith('.tif') or out_fn2.endswith('.rst')):
QMessageBox.critical(self, "Error",
"Please enter .rst or .tif extension in the name for Fitted Density Map in the CAL!")
return
if not map_checker.check_binary_map(self.deforestation_hrp):
QMessageBox.critical(None, "Error",
"'MAP OF DEFORESTATION IN THE CAL' must be a binary map (0 and 1) where the 1’s indicate deforestation.")
return
# Show "Processing" message
processing_message = "Processing data..."
self.progressDialog = QProgressDialog(processing_message, None, 0, 100, self)
# Change the font size
font = QFont()
font.setPointSize(9)
self.progressDialog.setFont(font)
self.progressDialog.setWindowTitle("Processing")
self.progressDialog.setWindowModality(Qt.WindowModal)
self.progressDialog.setMinimumDuration(0)
self.progressDialog.resize(400, 300)
self.progressDialog.show()
QApplication.processEvents()
try:
self.allocation_tool.execute_workflow_fit(directory, self.risk30_hrp,
self.municipality,self.deforestation_hrp, csv_name,
out_fn1,out_fn2)
QMessageBox.information(self, "Processing Completed", "Processing completed!")
self.progressDialog.close()
if self.checkBox.isChecked():
csv_basename = os.path.splitext(os.path.basename(csv_name))[0]
basename1 = os.path.splitext(os.path.basename(out_fn1))[0]
basename2 = os.path.splitext(os.path.basename(out_fn2))[0]
csv_layer = QgsVectorLayer(csv_name, csv_basename, "ogr")
layer1 = QgsRasterLayer(out_fn1, basename1)
layer2 = QgsRasterLayer(out_fn2, basename2)
layer1.setDataSource(os.path.join(directory, out_fn1), basename1, 'gdal')
layer2.setDataSource(os.path.join(directory, out_fn2), basename2, 'gdal')
#csv_layer.setDataSource(os.path.join(directory,csv_name), "UTF-8", "x", ";")
QgsProject.instance().addMapLayer(layer1)
QgsProject.instance().addMapLayer(layer2)
QgsProject.instance().addMapLayer(csv_layer)
except Exception as e:
self.progressDialog.close()
QMessageBox.critical(self, "Error", f"An error occurred during processing: {str(e)}")
def update_progress(self, value):
# Update QProgressDialog with the new value
if self.progressDialog is not None:
self.progressDialog.setValue(value)
######################################################################################################
class MCT_FIT_CAL_SCREEN(QtWidgets.QDialog, FORM_CLASS3):
def __init__(self, parent=None):
"""Constructor."""
super(MCT_FIT_CAL_SCREEN, self).__init__(parent)
# Store the initial directory path
self.initial_directory = os.getcwd()
# Set up the user interface from Designer through FORM_CLASS3.
self.setupUi(self)
# Workspace handling
if central_data_store.directory is not None and self.folder_entry is not None:
self.directory = central_data_store.directory
self.folder_entry.setText(str(central_data_store.directory))
self.AT_button4.clicked.connect(self.gotoat4)
self.Intro_button4.clicked.connect(self.gotointro4)
self.RMT_button4.clicked.connect(self.gotormt4)
self.doc_button.clicked.connect(self.openDocument)
self.select_folder_button.clicked.connect(self.select_working_directory)
self.mask_button.clicked.connect(lambda: self.selectRaster(self.mask_entry, 'Mask of Study Area'))
self.deforestation_hrp_button.clicked.connect(lambda: self.selectRaster(self.deforestation_hrp_entry, 'Map of Deforestation in the CAL'))
self.density_button.clicked.connect(lambda: self.selectRaster(self.density_entry, 'Deforestation Density Map'))
self.ok_button.clicked.connect(self.process_data4)
self.model_evaluation = ModelEvaluation()
self.model_evaluation.progress_updated.connect(self.update_progress)
self.directory = None
self.mask = None
self.deforestation_hrp = None
self.density = None
self.grid_area = None
self.grid_area_entry.setPlaceholderText('Type default 100000 or other number')
self.title = None
self.out_fn = None
self.out_fn_entry.setPlaceholderText('e.g., Plot_CAL.png')
self.raster_fn = None
self.raster_fn_entry.setPlaceholderText('e.g., Acre_Residuals_CAL.tif')
self.xmax = None
self.xmax = None
self.setWindowTitle("JNR Integrated Risk/Allocation Tool")
# Provide intitial settings for each comboBox
self.mask_entry.setStyleSheet(style_sheet)
self.deforestation_hrp_entry.setStyleSheet(style_sheet)
self.density_entry.setStyleSheet(style_sheet)
self.mask_entry.setCurrentIndex(-1)
self.deforestation_hrp_entry.setCurrentIndex(-1)
self.density_entry.setCurrentIndex(-1)
self.mask_entry.setFilters(QgsMapLayerProxyModel.RasterLayer)
self.deforestation_hrp_entry.setFilters(QgsMapLayerProxyModel.RasterLayer)
self.density_entry.setFilters(QgsMapLayerProxyModel.RasterLayer)
def gotoat4(self):
os.chdir(self.initial_directory)
at4 = AT_FIT_CAL_SCREEN()
stacked_widget.addWidget(at4)
stacked_widget.setCurrentIndex(stacked_widget.currentIndex() + 1)
def gotointro4(self):
os.chdir(self.initial_directory)
intro4 = IntroScreen()
stacked_widget.addWidget(intro4)
stacked_widget.setCurrentIndex(stacked_widget.currentIndex() + 1)
def gotormt4(self):
os.chdir(self.initial_directory)
rmt4 = RMT_FIT_CAL_SCREEN()
stacked_widget.addWidget(rmt4)
stacked_widget.setCurrentIndex(stacked_widget.currentIndex() + 1)
def openDocument(self):
pdf_path = os.path.join(os.path.dirname(__file__), "doc\\TestFitMA.pdf")
QDesktopServices.openUrl(QUrl.fromLocalFile(str(pdf_path)))
def select_working_directory(self):
data_folder = QFileDialog.getExistingDirectory(self, "Working Directory")
data_folder_path = Path(data_folder)
self.directory = str(data_folder_path)
self.folder_entry.setText(self.directory)
central_data_store.directory = self.directory
def selectRaster(self, comboBox, string):
"""
Opening the raster layer file and adding the path to the combobox
on end of the list with comboBox items.
:param comboBox: Qt combobox.
:type comboBox: QComboBox
"""
rast_path = QFileDialog.getOpenFileName(self, string)
index = comboBox.currentIndex()
comboBox.setAdditionalItems([rast_path[0]])
ind = comboBox.count() - 1
comboBox.setCurrentIndex(ind)
def process_data4(self):
try:
self.mask = self.mask_entry.currentLayer().source()
except Exception:
self.mask = self.mask_entry.currentText()
try:
self.deforestation_hrp = self.deforestation_hrp_entry.currentLayer().source()
except Exception:
self.deforestation_hrp = self.deforestation_hrp_entry.currentText()
try:
self.density = self.density_entry.currentLayer().source()
except Exception:
self.density = self.density_entry.currentText()
images = [self.mask, self.deforestation_hrp, self.density]
# Check if all images have the same resolution
resolutions = [map_checker.get_image_resolution(img) for img in images]
if len(set(resolutions)) != 1:
QMessageBox.critical(None, "Error", "All the input raster images must have the same spatial resolution!")
return
# Check if all images have the same number of rows and columns
dimensions = [map_checker.get_image_dimensions(img) for img in images]
if len(set(dimensions)) != 1:
QMessageBox.critical(None, "Error",
"All the input raster images must have the same number of rows and columns!")
return
if not self.mask or not self.deforestation_hrp or not self.density :
QMessageBox.critical(self, "Error", "Please select all input files!")
return
grid_area = self.grid_area_entry.text()
if not grid_area:
QMessageBox.critical(self, "Error", "Please enter the thiessen polygon grid area value!")
return
try:
self.grid_area = float(grid_area)
if not (0 < self.grid_area):
QMessageBox.critical(self, "Error", "Thiessen polygon grid area value should larger than 0!")
return
except ValueError:
QMessageBox.critical(self, "Error", "Thiessen polygon grid area value should be a valid number!")
return
xmax = self.xmax_entry.text()
if xmax.lower() != "default":
try:
xmax = float(xmax)
if xmax <= 0:
raise ValueError("The plot x-axis limit should be larger than 0!")
except ValueError:
QMessageBox.critical(self, "Error", "The plot x-axis limit should be a valid number or 'Default'!")
return
ymax = self.ymax_entry.text()
if ymax.lower() != "default":
try:
ymax = float(ymax)
if ymax <= 0:
raise ValueError("The plot y-axis limit should be larger than 0!")
except ValueError:
QMessageBox.critical(self, "Error", "The plot y-axis limit should be a valid number or 'Default'!")
return
title = self.title_entry.text()
if not title:
QMessageBox.critical(self, "Error", "Please enter the title of plot!")
return
directory = self.folder_entry.text()
out_fn = self.out_fn_entry.text()
if not out_fn:
QMessageBox.critical(self, "Error", "Please enter the name of plot!")
return
# Check if the out_fn has the correct file extension
if not (out_fn.endswith('.png') or out_fn.endswith('.jpg') or out_fn.endswith('.pdf') or out_fn.endswith(
'.svg') or out_fn.endswith('.eps') or out_fn.endswith('.ps') or out_fn.endswith('.tif')):
QMessageBox.critical(self, "Error",
"Please enter extension(.png/.jpg/.pdf/.svg/.eps/.ps/.tif) in the name of plot!")
return
raster_fn = self.raster_fn_entry.text()
if not raster_fn:
QMessageBox.critical(self, "Error", "Please enter the name for Residual Map!")
return
if not (raster_fn.endswith('.tif') or raster_fn.endswith('.rst')):
QMessageBox.critical(self, "Error",
"Please enter .rst or .tif extension in the name of Residual Map!")
return
if not map_checker.check_binary_map(self.mask):
QMessageBox.critical(None, "Error",
"'MASK OF THE NON-EXCLUDED JURISDICTION' must be a binary map (0 and 1) where the 1’s indicate areas inside the jurisdiction.")
return
if not map_checker.check_binary_map(self.deforestation_hrp):
QMessageBox.critical(None, "Error",
"'MAP OF DEFORESTATION IN THE CAL' must be a binary map (0 and 1) where the 1’s indicate deforestation.")
return
# Show "Processing" message
processing_message = "Processing data..."
self.progressDialog = QProgressDialog(processing_message, None, 0, 100, self)
# Change the font size
font = QFont()
font.setPointSize(9)
self.progressDialog.setFont(font)
self.progressDialog.setWindowTitle("Processing")
self.progressDialog.setWindowModality(Qt.WindowModal)
self.progressDialog.setMinimumDuration(0)
self.progressDialog.resize(400, 300)
self.progressDialog.show()
QApplication.processEvents()
try:
self.model_evaluation.set_working_directory(directory)
self.model_evaluation.create_mask_polygon(self.mask)
clipped_gdf = self.model_evaluation.create_thiessen_polygon(self.grid_area, self.mask,self.density, self.deforestation_hrp, out_fn,raster_fn)
self.model_evaluation.replace_ref_system(self.mask, raster_fn)
self.model_evaluation.create_plot(grid_area,clipped_gdf, title, out_fn, xmax, ymax)
self.model_evaluation.remove_temp_files()
if self.checkBox.isChecked():
basename = os.path.splitext(os.path.basename(raster_fn))[0]
layer = QgsRasterLayer(raster_fn, basename)
layer.setDataSource(os.path.join(directory, raster_fn), basename, 'gdal')
QgsProject.instance().addMapLayer(layer)
QMessageBox.information(self, "Processing Completed", "Processing completed!")
self.progressDialog.close()
except Exception as e:
self.progressDialog.close()
QMessageBox.critical(self, "Error", f"An error occurred during processing: {str(e)}")
def update_progress(self, value):
# Update QProgressDialog with the new value
if self.progressDialog is not None:
self.progressDialog.setValue(value)
######################################################################################################