-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathurban_sarca.py
649 lines (524 loc) · 24.1 KB
/
urban_sarca.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
# -*- coding: utf-8 -*-
"""
/***************************************************************************
UrbanSARCA
A QGIS plugin
Plugin for analysis of radioactive contamination ov vegetation cover in urban environment
Generated by Plugin Builder: http://g-sherman.github.io/Qgis-Plugin-Builder/
-------------------
begin : 2020-03-31
git sha : $Format:%H$
copyright : (C) 2020-2023 by Jakub Brom, ENKI o.p.s. Třeboň
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. *
* *
***************************************************************************/
"""
from qgis.PyQt.QtCore import QSettings, QTranslator, QCoreApplication, Qt, QUrl
from qgis.PyQt.QtGui import QIcon, QDesktopServices, QImage, QPixmap
from qgis.PyQt.QtWidgets import QAction, QFileDialog, QComboBox, QPushButton, QMessageBox, QSpinBox, QTableWidgetItem
# Initialize Qt resources from file resources.py
from .resources import *
from qgis.core import Qgis, QgsMapLayerProxyModel
# Import the code for the DockWidget
from .urban_sarca_dockwidget import UrbanSARCADockWidget
import sys
import urllib.request
from .urban_sarca_lib import *
from .overlap_clip import *
from .SEBCS_lib import GeoIO, VegIndices
geo = GeoIO()
vi = VegIndices()
class UrbanSARCA:
"""QGIS Plugin Implementation."""
def __init__(self, iface):
"""Constructor.
:param iface: An interface instance that will be passed to this class
which provides the hook by which you can manipulate the QGIS
application at run time.
:type iface: QgsInterface
"""
# Save reference to the QGIS interface
self.iface = iface
# initialize plugin directory
self.plugin_dir = os.path.dirname(__file__)
# initialize locale
self.locale = QSettings().value('locale/userLocale')[0:2]
locale_path = os.path.join(
self.plugin_dir,
'i18n',
'UrbanSARCA_{}.qm'.format(self.locale))
if os.path.exists(locale_path):
self.translator = QTranslator()
self.translator.load(locale_path)
QCoreApplication.installTranslator(self.translator)
# Declare instance attributes
self.actions = []
self.menu = self.tr(u'&Urban Green SARCA')
# TODO: We are going to let the user set this up in a future iteration
self.toolbar = self.iface.addToolBar(u'Urban Green SARCA')
self.toolbar.setObjectName(u'Urban Green SARCA')
# print "** INITIALIZING UrbanSARCA"
self.pluginIsActive = False
self.dockwidget = None
# Initial output folder path
self.out_folder_path = os.path.expanduser("~")
# noinspection PyMethodMayBeStatic
def tr(self, message):
"""Get the translation for a string using Qt translation API.
We implement this ourselves since we do not inherit QObject.
:param message: String for translation.
:type message: str, QString
:returns: Translated version of message.
:rtype: QString
"""
# noinspection PyTypeChecker,PyArgumentList,PyCallByClass
return QCoreApplication.translate('Urban Green SARCA', message)
def add_action(
self,
icon_path,
text,
callback,
enabled_flag=True,
add_to_menu=True,
add_to_toolbar=True,
status_tip=None,
whats_this=None,
parent=None):
"""Add a toolbar icon to the toolbar.
:param icon_path: Path to the icon for this action. Can be a resource
path (e.g. ':/plugins/foo/bar.png') or a normal file system path.
:type icon_path: str
:param text: Text that should be shown in menu items for this action.
:type text: str
:param callback: Function to be called when the action is triggered.
:type callback: function
:param enabled_flag: A flag indicating if the action should be enabled
by default. Defaults to True.
:type enabled_flag: bool
:param add_to_menu: Flag indicating whether the action should also
be added to the menu. Defaults to True.
:type add_to_menu: bool
:param add_to_toolbar: Flag indicating whether the action should also
be added to the toolbar. Defaults to True.
:type add_to_toolbar: bool
:param status_tip: Optional text to show in a popup when mouse pointer
hovers over the action.
:type status_tip: str
:param parent: Parent widget for the new action. Defaults None.
:type parent: QWidget
:param whats_this: Optional text to show in the status bar when the
mouse pointer hovers over the action.
:returns: The action that was created. Note that the action is also
added to self.actions list.
:rtype: QAction
"""
icon = QIcon(icon_path)
action = QAction(icon, text, parent)
action.triggered.connect(callback)
action.setEnabled(enabled_flag)
if status_tip is not None:
action.setStatusTip(status_tip)
if whats_this is not None:
action.setWhatsThis(whats_this)
if add_to_toolbar:
self.toolbar.addAction(action)
if add_to_menu:
self.iface.addPluginToMenu(
self.menu,
action)
self.actions.append(action)
return action
def initGui(self):
"""Create the menu entries and toolbar icons inside the QGIS GUI."""
icon_path = ':/plugins/urban_sarca/icon.png'
self.add_action(
icon_path,
text=self.tr(u'Urban Green SARCA'),
callback=self.run,
parent=self.iface.mainWindow())
if not self.pluginIsActive:
self.pluginIsActive = True
# dockwidget may not exist if:
# first run of plugin
# removed on close (see self.onClosePlugin method)
if self.dockwidget == None:
# Create the dockwidget (after translation) and keep reference
self.dockwidget = UrbanSARCADockWidget()
# Add rows to reference tresholds table
self.dockwidget.pb_plus.clicked.connect(lambda: self.tableAddRow(self.dockwidget.tw_reflevel))
# Remove rows from reference tresholds table
self.dockwidget.pb_minus.clicked.connect(lambda: self.tableRemoveRow(self.dockwidget.tw_reflevel))
# Help
self.dockwidget.buttonBox.helpRequested.connect(self.pluginHelp)
# ----------------------------------------------------------------
def setCboxEmpty(self, comboBox):
"""Setting of empty value (text) in comboBoxes"""
comboBox.setAdditionalItems([""])
ind = comboBox.count() - 1
comboBox.setCurrentIndex(ind)
def pluginHelp(self):
"""Open the help file.
"""
help_file = os.path.join(self.plugin_dir, "help", "build",
"html", "index.html")
help_file_norm = os.path.normpath(help_file)
try:
if sys.platform != "win32":
QDesktopServices.openUrl(QUrl(help_file_norm,
QUrl.TolerantMode))
else:
print(help_file)
print(help_file_norm)
os.startfile(help_file_norm)
except IOError:
self.iface.messageBar().pushMessage(self.tr("Help error"),
self.tr("Ooops, an error occured during help file"
" opening..."), level=Qgis.Warning, duration=5)
def tableRemoveRow(self, table):
"""Remove row from table"""
# Get row counts:
row_count = table.rowCount()
table.setRowCount(row_count - 1)
def tableAddRow(self, table):
"""
Add row to TableWidget. The first column is Reference level treshold description, the second is value (Bq/m2).
:param table: QTableWidget
:return:
"""
# Set column witdth
# table.setColumnWidth(0, 250)
# Get row counts:
row_count = table.rowCount()
# Set new row
table.setRowCount(row_count + 1)
# Add labels and spinbox for RL values
# Create label
label = 'RL {num}'.format(num=str(row_count + 1))
# Add label to table
table.setItem(row_count, 0, QTableWidgetItem(label))
# Add Spinbox
spin = QSpinBox()
spin.setMaximum(2147483647)
table.setCellWidget(row_count, 1, spin)
def selectFile(self, comboBox):
"""
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
"""
try:
rast_path = QFileDialog.getOpenFileName(None,
self.tr(
"Select file"),
self.out_folder_path,
"Images (*.*);; "
"GeoTIFF (*.tif);; "
"Idrisi Raster (*.rst);; "
"Erdas Imagine (*.img);; "
"GDAL Virtual (*.vrt);; "
"ENVI (*.hdr)")
comboBox.setAdditionalItems([rast_path[0]])
ind = comboBox.count() - 1
comboBox.setCurrentIndex(ind)
except FileNotFoundError:
self.iface.messageBar().pushMessage(self.tr("Path error"),
self.tr(
"Selected file has not "
"been found."),
level=Qgis.Warning)
def outFolder(self):
"""
Set output folder path.
"""
self.dockwidget.le_out_folder.clear()
try:
self.out_folder_path = QFileDialog.getExistingDirectory(
None,
self.tr("Select output folder"),
self.out_folder_path)
self.dockwidget.le_out_folder.setText(
str(self.out_folder_path))
except Exception:
self.iface.messageBar().pushMessage(
self.tr("Path error"),
self.tr(
"Output folder path has not been selected"),
level=Qgis.Warning)
def onClosePlugin(self):
"""Cleanup necessary items here when plugin dockwidget is closed"""
#print "** CLOSING UrbanSARCA"
# disconnects
self.dockwidget.closingPlugin.disconnect(self.onClosePlugin)
# remove this statement if dockwidget is to remain
# for reuse if plugin is reopened
# Commented next statement since it causes QGIS crashe
# when closing the docked window:
# self.dockwidget = None
self.dockwidget.le_out_folder.clear()
self.dockwidget.sbox_precip.setValue(0.00)
# self.dockwidget.sbox_ru1.setValue(5000)
# self.dockwidget.sbox_ru2.setValue(3000000)
self.dockwidget.sbox_hl.setValue(1000)
self.dockwidget.cbox_cont.setCurrentIndex(0)
self.dockwidget.rb_precip_konst.setChecked(True)
self.pluginIsActive = False
def unload(self):
"""Removes the plugin menu item and icon from QGIS GUI."""
#print "** UNLOAD UrbanSARCA"
for action in self.actions:
self.iface.removePluginMenu(
self.tr(u'&UrbanSARCA'),
action)
self.iface.removeToolBarIcon(action)
# remove the toolbar
del self.toolbar
def calculate(self):
"""Processing of calculation"""
# Import layers and data
# Rasters
try:
red_index = self.dockwidget.cbox_red.currentIndex()
red_path = self.dockwidget.cbox_red.layer(red_index).source()
except Exception:
red_path = self.dockwidget.cbox_red.currentText()
if red_path is None or red_path == "":
self.iface.messageBar().pushMessage(
self.tr("Path error"),
self.tr("Path to RED band has not been selected"),
level=Qgis.Warning)
sys.tracebacklimit = None
raise FileNotFoundError(self.tr("Path to RED band has not been selected"))
# TODO: vyresit vyjimky - prekryv vypisu vyjimky...
try:
nir_index = self.dockwidget.cbox_nir.currentIndex()
nir_path = self.dockwidget.cbox_nir.layer(nir_index).source()
except Exception:
nir_path = self.dockwidget.cbox_nir.currentText()
if nir_path is None or nir_path == "":
self.iface.messageBar().pushMessage(
self.tr("Path error"),
self.tr("Path to NIR band has not been selected"),
level=Qgis.Warning)
sys.tracebacklimit = None
raise FileNotFoundError(self.tr("Path to NIR band has not been "
"selected"))
try:
depo_index = self.dockwidget.cbox_depo.currentIndex()
depo_path = self.dockwidget.cbox_depo.layer(depo_index).source()
except Exception:
depo_path = self.dockwidget.cbox_depo.currentText()
if depo_path is None or depo_path == "":
self.iface.messageBar().pushMessage(
self.tr("Path error"),
self.tr("Path to radioactive contamination layer has "
"not been selected"),
level=Qgis.Warning)
sys.tracebacklimit = None
raise FileNotFoundError(self.tr("Path to radioactive "
"contamination layer "
"has not been selected"))
# Precipitation raster
if self.dockwidget.rb_precip_konst.isChecked() == True:
precip = self.dockwidget.sbox_precip.value()
precip_path = None
else:
try:
precip_index = self.dockwidget.cbox_precip.currentIndex()
precip_path = self.dockwidget.cbox_precip.layer(
precip_index).source()
except Exception:
precip_path = self.dockwidget.cbox_precip.currentText()
if precip_path is None or precip_path == "":
self.iface.messageBar().pushMessage(
self.tr("Path error"),
self.tr("Path to precipitation layer has not been "
"selected"),
level=Qgis.Warning)
sys.tracebacklimit = None
raise FileNotFoundError(self.tr("Path to precipitation layer "
"has not been selected"))
# Radionuclide
radio_index = self.dockwidget.cbox_cont.currentIndex()
if radio_index == 0:
radionuclide = 1.0
elif radio_index == 1 or radio_index == 3:
radionuclide = 2.0
elif radio_index == 2:
radionuclide = 0.5
else:
radionuclide = 1.0
# Constants
r_count = self.dockwidget.tw_reflevel.rowCount()
ref_levels_list = list([self.dockwidget.tw_reflevel.cellWidget(i, 1).value() for i in range(r_count)])
ref_names_list = list([self.dockwidget.tw_reflevel.item(i, 0).text() for i in range(r_count)])
ref_levels_dict = {ref_names_list[i]: ref_levels_list[i] for i in range(len(ref_levels_list))}
hyg_lim = self.dockwidget.sbox_hl.value()
# Output path
self.out_folder = self.dockwidget.le_out_folder.text()
# If outpath is empty, the home path is selected
if self.out_folder is None or self.out_folder == "":
self.out_folder = os.path.expanduser("~")
# Calculation
# TODO: zkusit vyresit mazani docasnych souboru tady
if precip_path != None:
# 1. Layers clipping
in_lyrs = [red_path, nir_path, depo_path, precip_path]
(cl_red, cl_nir, cl_depo, cl_precip) = clipOverlappingArea(
in_lyrs, tmp_out=True)
# 2. Layers import to Numpy arrays
in_red = geo.rasterToArray(cl_red)
in_nir = geo.rasterToArray(cl_nir)
in_depo = geo.rasterToArray(cl_depo)
precip = geo.rasterToArray(cl_precip)
else:
# 1. Layers clipping
in_lyrs = [red_path, nir_path, depo_path]
(cl_red, cl_nir, cl_depo) = clipOverlappingArea(in_lyrs,
tmp_out=True)
# 2. Layers import to Numpy arrays
in_red = geo.rasterToArray(cl_red)
in_nir = geo.rasterToArray(cl_nir)
in_depo = geo.rasterToArray(cl_depo)
in_depo = np.nan_to_num(in_depo)
# Reading geographic information on layers
(gtransf, prj, x_size, y_size, EPSG) = geo.readGeo(cl_red)
# 2. Veg. indices
ndvi = vi.viNDVI(in_red, in_nir)
msavi = vi.viMSAVI(in_red, in_nir)
lai = vi.LAI(in_red, in_nir, self.lai_method)
biom = vi.biomass_sat(ndvi)
# 3. IF and radioactive deposition calculation
IF = interceptFactor(lai, precip, biom, radionuclide)
dep_biom = contBiomass(in_depo, IF)
dep_soil = contSoil(in_depo, IF)
cont_weight = contMass(dep_biom, biom)
# 4. RU and hyg_lim masks
mask_HL = hygLimit(cont_weight, hyg_lim)
mask_RU = referLevel(in_depo, ref_levels_dict)
# 5. Layers export
output = {
"Biomass": biom,
"Intercept_factor": IF,
"Veg_contamination": dep_biom,
"Soil_contamination": dep_soil,
"Mass_contamination": cont_weight,
"Mask_hyg_lim": mask_HL,
"Mask_ref_levels": mask_RU
}
# "LAI": lai,
# "NDVI": ndvi,
# "MSAVI": msavi
self.outlyrs = list(output.values())
self.outnames = list(output.keys())
geo.arrayToRast(self.outlyrs, self.outnames, prj, gtransf, EPSG,
self.out_folder)
# Import results to QGIS legend/canvas
self.iface.messageBar().clearWidgets()
widget = self.iface.messageBar().createMessage("Info", self.tr(
"Calculation has been done. Do you want to load "
"calculated layers in to QGIS?"))
button = QPushButton(widget)
button.setText(self.tr("Load layers"))
button.pressed.connect(self.loadRasters)
widget.layout().addWidget(button)
self.iface.messageBar().pushWidget(widget, Qgis.Info)
def loadRasters(self):
"""Uploading of the results (calculated layers) in to the
QGIS legend.
"""
out_suffix = ".tif"
# List of output files paths
for i in range(0, len(self.outlyrs)):
try:
out_file = os.path.join(self.out_folder,
self.outnames[i] + out_suffix) # construction of the path to the resulted layer
self.iface.addRasterLayer(out_file, self.outnames[i]) # opening the resulted layer
except Exception:
self.iface.messageBar().pushMessage("Info",
self.tr("File " + self.outnames[i] +
" has not been uploaded in to QGIS."),
level=Qgis.Warning)
self.iface.messageBar().clearWidgets()
def showInfo(self):
# msgbox text
if self.locale == "cs":
info_text = "Vývoj programu Urban Green SARCA byl " \
"finančně podpořen projektem Ministerstva " \
"vnitra České republiky VH20172020015"
else:
info_text = self.tr("Urban Green SARCA plug-in "
"development has been supported by "
"project of Ministry of the Interior "
"of the Czech Republic No. "
"VH20172020015")
# set path to msgbox icon
# icon_path = 'https://upload.wikimedia.org/wikipedia/commons/7/79/MV_%C4%8CR.png'
# data = urllib.request.urlopen(icon_path).read()
localdir = os.path.dirname(__file__)
data = os.path.join(localdir, "MV_icon.png")
# Create icon
image = QImage()
image.load(data)
pixmap = QPixmap(image).scaledToHeight(128,
Qt.SmoothTransformation)
# MsgBox
msg_box = QMessageBox()
msg_box.setIconPixmap(pixmap)
msg_box.setText(info_text)
msg_box.setWindowTitle(self.tr("Acknowledgement"))
msg_box.exec()
#--------------------------------------------------------------------------
def run(self):
"""Run method that loads and starts the plugin"""
# print "** STARTING UrbanSARCA"
self.showInfo()
# Set path to out folder
self.dockwidget.pb_out.clicked.connect(self.outFolder)
# Initial setting of the empty cboxes
self.setCboxEmpty(self.dockwidget.cbox_red)
self.setCboxEmpty(self.dockwidget.cbox_nir)
self.setCboxEmpty(self.dockwidget.cbox_depo)
self.setCboxEmpty(self.dockwidget.cbox_precip)
# If precipitation is constant the cbox for precipitation
# raster is empty
self.dockwidget.rb_precip_konst.toggled.connect(lambda:
self.setCboxEmpty(self.dockwidget.cbox_precip))
self.dockwidget.rb_precip_rast.toggled.connect(lambda:
self.dockwidget.cbox_precip.setCurrentIndex(0))
# If raster of precipitation is selected, value in spinbox is set
# to 0.0
self.dockwidget.rb_precip_rast.toggled.connect(lambda:
self.dockwidget.sbox_precip.setValue(0.00))
# Read list of names and layers paths from QGIS legend
self.dockwidget.cbox_red.setFilters(QgsMapLayerProxyModel.RasterLayer)
self.dockwidget.cbox_nir.setFilters(QgsMapLayerProxyModel.RasterLayer)
self.dockwidget.cbox_depo.setFilters(QgsMapLayerProxyModel.RasterLayer)
self.dockwidget.cbox_precip.setFilters(
QgsMapLayerProxyModel.RasterLayer)
# Set path to selected raster files to CBoxes
self.dockwidget.pb_red.clicked.connect(lambda:
self.selectFile(self.dockwidget.cbox_red))
self.dockwidget.pb_nir.clicked.connect(
lambda: self.selectFile(self.dockwidget.cbox_nir))
self.dockwidget.pb_depo.clicked.connect(
lambda: self.selectFile(self.dockwidget.cbox_depo))
self.dockwidget.pb_precip.clicked.connect(
lambda: self.selectFile(self.dockwidget.cbox_precip))
# Set LAI method
self.lai_method = self.dockwidget.cbox_lai.currentIndex()
# Calculate
self.dockwidget.buttonBox.accepted.connect(self.calculate)
# connect to provide cleanup on closing of dockwidget
self.dockwidget.closingPlugin.connect(self.onClosePlugin)
# show the dockwidget
# TODO: fix to allow choice of dock location
self.iface.addDockWidget(Qt.RightDockWidgetArea, self.dockwidget)
self.dockwidget.show()