-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdam_raster.py
781 lines (648 loc) · 33.6 KB
/
dam_raster.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
from __future__ import unicode_literals
from __future__ import absolute_import
# system modules
import os
import math
from datetime import datetime
import tempfile
import webbrowser
# QGIS modules
from qgis.core import *
from qgis.gui import *
from qgis.PyQt.QtCore import *
from qgis.PyQt.QtGui import *
from qgis.PyQt.QtWidgets import *
from qgis.PyQt import uic
# promaides modules
from .interpolate import RasterInterpolator
from .raster import SimpleRasterWriter
from .environment import get_ui_path
from .version import *
from .utils import *
UI_PATH = get_ui_path('ui_raster_export.ui')
# This plugin exports the 2D-floodplain raster file(s) for the HYD-module of ProMaIdes;
# The polygons are created as temporary layer
# TODO Change to existing polygon shp
class PluginDialog(QDialog):
rasterAdded = pyqtSignal(int, QgsGeometry)
rasterUpdated = pyqtSignal(int, QgsGeometry)
rasterRemoved = pyqtSignal(int)
ClosingSignal = pyqtSignal()
RejectSignal = pyqtSignal()
xllRole = 111 # Those numbers only describe an ID but not the actual values
yllRole = 112
nrRole = 113
ncRole = 114
drcRole = 115
def __init__(self, iface, parent=None, flags=Qt.WindowFlags()):
QDialog.__init__(self, parent, flags)
uic.loadUi(UI_PATH, self)
self.iface = iface
self.ecnLayerBox.setFilters(QgsMapLayerProxyModel.RasterLayer)
self.popLayerBox.setFilters(QgsMapLayerProxyModel.RasterLayer)
self.AreaLayerBox.setFilters(QgsMapLayerProxyModel.PolygonLayer)
# The module consists of two input options ecn/ pop. The lines below set the default that none of them are chosen in the beginning.
# The user has to choose one of them. The two bottom functions will make sure that only one of the options can be chosen.
self.mGroupBox_ecn.clicked.connect(self.check_mGroupBox_ecn)
self.mGroupBox_pop.clicked.connect(self.check_mGroupBox_pop)
self.mGroupBox_ecn.setChecked(True)
self.picker = QgsMapToolEmitPoint(self.iface.mapCanvas())
self.addButton.setEnabled(False)
self.zoomButton.setEnabled(False)
self.removeButton.setEnabled(False)
self.ExportButton.setEnabled(False)
self.groupBox.setEnabled(False)
self.ImportButton.setEnabled(False)
self.AreaLayerBox.setLayer(None)
self.ecnLayerBox.setLayer(None)
self.popLayerBox.setLayer(None)
self.removeButton.clicked.connect(self.removeRasterItems)
self.removeButton.setAutoDefault(False)
self.listWidget.currentRowChanged.connect(self.updateRasterPropertiesGroup)
self.ecnLayerBox.layerChanged.connect(self.updateECNBox)
self.popLayerBox.layerChanged.connect(self.updatePOPBox)
self.AreaLayerBox.layerChanged.connect(self.UpdateImportButtons)
self.pickButton.clicked.connect(self.enableMapPicker)
self.pickButton.setAutoDefault(False)
self.browseButton.clicked.connect(self.onBrowseButtonClicked)
self.browseButton.setAutoDefault(False)
self.mGroupBox_ecn.setChecked(True)
self.popNaNBox.setEnabled(False)
self.popTypeBox.setEnabled(False)
self.popUnitTransBox.setEnabled(False)
self.popLayerBox.setEnabled(False)
self.label_20.setEnabled(False)
self.label.setEnabled(False)
self.label_12.setEnabled(False)
self.label_21.setEnabled(False)
self.HelpButton.clicked.connect(self.Help)
def Help(self):
webbrowser.open("https://promaides.myjetbrains.com/youtrack/articles/PMDP-A-38/DAM-Raster-export")
def closeEvent(self, event):
self.ClosingSignal.emit()
def reject(self):
self.RejectSignal.emit()
def UpdateImportButtons(self):
if self.AreaLayerBox.currentLayer():
self.ImportButton.setEnabled(True)
else:
self.ImportButton.setEnabled(False)
def check_mGroupBox_ecn(self):
self.mGroupBox_pop.setChecked(False)
self.ecnNaNBox.setEnabled(True)
self.ecndeltaBox.setEnabled(True)
def check_mGroupBox_pop(self):
self.mGroupBox_ecn.setChecked(False)
self.popNaNBox.setEnabled(True)
self.popTypeBox.setEnabled(True)
self.popUnitTransBox.setEnabled(True)
self.popLayerBox.setEnabled(True)
self.label_20.setEnabled(True)
self.label.setEnabled(True)
self.label_12.setEnabled(True)
self.label_21.setEnabled(True)
def enableMapPicker(self, clicked):
# Triggered after 'pick coordinates from Map ...' and will link to QG functino to read coordinates from a map click.
if clicked:
self.picker.canvasClicked.connect(self.onMapClicked)
self.iface.mapCanvas().setMapTool(self.picker)
else:
self.picker.canvasClicked.disconnect(self.onMapClicked)
self.iface.mapCanvas().unsetMapTool(self.picker)
def onMapClicked(self, point, button):
if button == Qt.LeftButton:
self.xllBox.setValue(point.x())
self.yllBox.setValue(point.y())
self.xllBox.editingFinished.emit()
def ecnLayer(self):
# RS: This command will make the currently chosen layer in qgis the layer now defined as lucLayer
return self.ecnLayerBox.currentLayer()
def ecnNaN(self):
# This will define the number in the nanBox in theQGIS GUI as ecnNaN
return self.ecnNaNBox.value()
def ecnDelta(self):
# This defines the number in the deltaMobImmobBox as the difference between values for mobile and immobile
return self.ecndeltaBox.value()
def popLayer(self):
# RS: This command will make the currently chosen layer in qgis the layer now defined as lucLayer
return self.popLayerBox.currentLayer()
def popNaN(self):
# This will define the number in the nanBox in theQGIS GUI as popnNaN (*) maybe useless, question asked to root
return self.popNaNBox.value()
def popType(self):
# This will define the number in the nanBox in theQGIS GUI as popnNaN (*) maybe useless, question asked to root
return self.popTypeBox.value()
def popUnitTrans(self):
# This will define the number in the nanBox in theQGIS GUI as popnNaN (*) maybe useless, question asked to root
return self.popUnitTransBox.value()
def onBrowseButtonClicked(self):
# Definition of the directory you will be lead to when choosing the output folder.
# Naming the heading of the window opening
# Covering the case of no file/folder chosen
currentFolder = self.folderEdit.text()
folder = QFileDialog.getExistingDirectory(self.iface.mainWindow(), 'DAM Raster Export', currentFolder)
if folder != '':
self.folderEdit.setText(folder)
self.folderEdit.editingFinished.emit()
def outFolder(self):
return self.folderEdit.text()
def updateECNBox(self, layer):
# Enables the option for user to change the layer which is basis for raster input
if not layer:
self.addButton.setEnabled(False)
return
self.addButton.setEnabled(True)
self.groupBox.setEnabled(True)
############################################
# raster settings
self.xllBox.setEnabled(False)
self.yllBox.setEnabled(False)
self.pickButton.setEnabled(False)
self.nrBox.setEnabled(False)
self.ncBox.setEnabled(False)
self.drcBox.setEnabled(False)
self.ExportButton.setEnabled(False)
# ecn specific settings
self.ecnNaNBox.setEnabled(True)
self.ecndeltaBox.setEnabled(True)
#############################################
def updatePOPBox(self, layer):
# Enables the option for user to change the layer which is basis for raster input
if not layer:
self.addButton.setEnabled(False)
return
self.addButton.setEnabled(True)
self.groupBox.setEnabled(True)
############################################
# raster settings
self.xllBox.setEnabled(False)
self.yllBox.setEnabled(False)
self.pickButton.setEnabled(False)
self.nrBox.setEnabled(False)
self.ncBox.setEnabled(False)
self.drcBox.setEnabled(False)
self.ExportButton.setEnabled(False)
# ecn specific settings
self.popNaNBox.setEnabled(True)
self.popTypeBox.setEnabled(True)
self.popUnitTransBox.setEnabled(True)
#############################################
def removeRasterItems(self):
# removes raster item from listWidget and the corresponding values from groupBox
# if no more rasters in the widget list raster settings will be disabled
for item in self.listWidget.selectedItems():
row = self.listWidget.row(item)
self.listWidget.takeItem(row)
self.rasterRemoved.emit(int(row + 1))
if self.listWidget.count() == 0:
self.zoomButton.setEnabled(False)
self.removeButton.setEnabled(False)
self.ExportButton.setEnabled(False)
self.groupBox.setEnabled(False)
############################################
#raster settings
self.xllBox.setEnabled(False)
self.yllBox.setEnabled(False)
self.pickButton.setEnabled(False)
self.nrBox.setEnabled(False)
self.ncBox.setEnabled(False)
self.drcBox.setEnabled(False)
self.ExportButton.setEnabled(False)
#############################################
def updateRasterPropertiesGroup(self, row):
# used when new properties are added to raster settings to automatically update bounding box
item = self.listWidget.item(row)
if item is None:
return
self.xllBox.setValue(item.data(PluginDialog.xllRole))
self.yllBox.setValue(item.data(PluginDialog.yllRole))
self.nrBox.setValue(item.data(PluginDialog.nrRole))
self.ncBox.setValue(item.data(PluginDialog.ncRole))
self.drcBox.setValue(item.data(PluginDialog.drcRole))
class DAMRasterExport(object):
def __init__(self, iface):
self.iface = iface
self.dialog = None
self.cancel = False
self.previewLayer = None
self.act = QAction('DAM Raster Export', iface.mainWindow())
self.act.triggered.connect(self.execDialog)
def initGui(self, menu=None):
if menu is not None:
menu.addAction(self.act)
else:
self.iface.addToolBarIcon(self.act)
def unload(self, menu=None):
if menu is None:
menu.removeAction(self.act)
else:
self.iface.removeToolBarIcon(self.act)
def execDialog(self):
# the function execDialog builds the backbone for the possible options to click in the plugin GUI
# for every button pressed it connects to a specific other function.
"""
"""
self.dialog = PluginDialog(self.iface, self.iface.mainWindow())
self.dialog.pushButton_ok.clicked.connect(self.execTool)
self.dialog.pushButton_ok.setAutoDefault(False)
self.dialog.pushButton_cancel.clicked.connect(self.quitDialog)
self.dialog.pushButton_cancel.setAutoDefault(False)
self.dialog.rasterAdded.connect(self.addRasterBounds)
self.dialog.rasterUpdated.connect(self.updateRasterBounds)
self.dialog.rasterRemoved.connect(self.removeRasterBounds)
self.dialog.setModal(False)
self.dialog.ExportButton.clicked.connect(self.SaveasPolygon)
self.dialog.addButton.clicked.connect(self.addNewRasterItem)
self.dialog.addButton.setAutoDefault(False)
self.dialog.ImportButton.clicked.connect(self.ImportAreaFromPolygon)
self.dialog.zoomButton.clicked.connect(self.zoomToRaster)
self.dialog.zoomButton.setAutoDefault(False)
self.dialog.ClosingSignal.connect(self.quitDialog)
self.dialog.RejectSignal.connect(self.quitDialog)
self.dialog.xllBox.editingFinished.connect(self.saveRasterProperties)
self.dialog.yllBox.editingFinished.connect(self.saveRasterProperties)
self.dialog.drcBox.editingFinished.connect(self.saveRasterProperties)
self.dialog.nrBox.editingFinished.connect(self.saveRasterProperties)
self.dialog.ncBox.editingFinished.connect(self.saveRasterProperties)
self.previewLayer = QgsVectorLayer('Polygon', 'ProMaIDes_DAM_Raster', 'memory')
self.previewLayer.setCrs(QgsCoordinateReferenceSystem(self.iface.mapCanvas().mapSettings().destinationCrs().authid()))
self.previewLayer.dataProvider().addAttributes([QgsField("xll", QVariant.Double),
QgsField("yll", QVariant.Double),
QgsField("dy", QVariant.Double),
QgsField("dx", QVariant.Double),
QgsField("nr", QVariant.Double),
QgsField("nc", QVariant.Double)])
self.previewLayer.updateFields()
# set layer properties
my_symbol = QgsFillSymbol.createSimple({'color': 'black', 'outline_color': 'blue', 'outline_width': '0.8',
'style':'no'})
self.previewLayer.renderer().setSymbol(my_symbol)
QgsProject.instance().addMapLayer(self.previewLayer)
self.act.setEnabled(False)
self.dialog.show()
def scheduleAbort(self):
self.cancel = True
ImportFromPolygon = False
def ImportAreaFromPolygon(self):
self.ImportFromPolygon = True
self.addNewRasterItem()
def zoomToRaster(self):
# RS: Reacts when zoomButton is pressed and changes bounding box to the raster settings entered in raster settings.
# item = self.listWidget.currentItem()
item = self.dialog.listWidget.currentItem()
xll = item.data(PluginDialog.xllRole) # RS only rectangular grids
yll = item.data(PluginDialog.yllRole)
nr = item.data(PluginDialog.nrRole) # RS raster number of cells per row and column
nc = item.data(PluginDialog.ncRole) # RS raster number of cells per row and column
drc = item.data(PluginDialog.drcRole) # RS delta row and column cell
bb = self.polygon(xll, yll, (nr * drc), (nc * drc)).boundingBox()
self.dialog.iface.mapCanvas().setExtent(bb)
self.dialog.iface.mapCanvas().refresh()
def addNewRasterItem(self):
# activated once a new raster is added. default values defined below are filled in
if self.ImportFromPolygon == True:
try:
layer = self.dialog.AreaLayerBox.currentLayer()
features = layer.getFeatures()
for i, f in enumerate(features):
num = self.dialog.listWidget.count() + 1
item = QListWidgetItem('raster_{:d}'.format(num))
item.setData(PluginDialog.xllRole, f.attribute("xll"))
item.setData(PluginDialog.yllRole, f.attribute("yll"))
item.setData(PluginDialog.nrRole, f.attribute("nr"))
item.setData(PluginDialog.ncRole, f.attribute("nc"))
item.setData(PluginDialog.drcRole, f.attribute("dy"))
item.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEditable | Qt.ItemIsEnabled)
self.dialog.removeButton.setEnabled(True)
self.dialog.ExportButton.setEnabled(True)
self.dialog.zoomButton.setEnabled(True)
self.dialog.groupBox.setEnabled(True)
############################################
# raster settings
self.dialog.xllBox.setEnabled(True)
self.dialog.yllBox.setEnabled(True)
self.dialog.pickButton.setEnabled(True)
self.dialog.drcBox.setEnabled(True)
self.dialog.nrBox.setEnabled(True)
self.dialog.ncBox.setEnabled(True)
self.dialog.ExportButton.setEnabled(True)
#############################################
polygon = self.polygon(0.0, 0.0, 100.0, 100.0)
self.dialog.rasterAdded.emit(int(self.dialog.listWidget.count() + 1), polygon)
self.dialog.listWidget.addItem(item)
self.dialog.listWidget.setCurrentItem(item)
self.saveRasterProperties()
if i == layer.featureCount() - 1:
self.ImportFromPolygon = False
return
except:
self.iface.messageBar().pushCritical(
'DAM raster Export',
'Area Cannot be Imported from Polygon !'
)
self.ImportFromPolygon = False
return
num = self.dialog.listWidget.count() + 1
item = QListWidgetItem('raster_{:d}'.format(num))
item.setData(PluginDialog.xllRole, -157230) # The first argument refers back to an id, the second one to the actual value
item.setData(PluginDialog.yllRole, 1066410)
item.setData(PluginDialog.drcRole, 100.0) # 25
item.setData(PluginDialog.nrRole, 75) # 100
item.setData(PluginDialog.ncRole, 100) # 120
item.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEditable | Qt.ItemIsEnabled)
self.dialog.removeButton.setEnabled(True)
self.dialog.ExportButton.setEnabled(True)
self.dialog.zoomButton.setEnabled(True)
self.dialog.groupBox.setEnabled(True)
############################################
# raster settings
self.dialog.xllBox.setEnabled(True)
self.dialog.yllBox.setEnabled(True)
self.dialog.pickButton.setEnabled(True)
self.dialog.drcBox.setEnabled(True)
self.dialog.nrBox.setEnabled(True)
self.dialog.ncBox.setEnabled(True)
self.dialog.ExportButton.setEnabled(True)
#############################################
polygon = self.polygon(0.0, 0.0, 100.0, 100.0)
self.dialog.rasterAdded.emit(int(self.dialog.listWidget.count() + 1), polygon)
self.dialog.listWidget.addItem(item)
self.dialog.listWidget.setCurrentItem(item)
self.saveRasterProperties()
def polygon(self, xll, yll, dx, dy):
# Function for polygon in format that QG can pick up
poly = [QgsPointXY(xll, yll),
QgsPointXY(xll + dx, yll),
QgsPointXY(xll + dx, yll + dy),
QgsPointXY(xll, yll + dy)]
return QgsGeometry.fromPolygonXY([poly])
def SaveasPolygon(self):
try:
original = self.previewLayer
currentFolder = QgsProject.instance().homePath()
originalpath = QFileDialog.getExistingDirectory(self.iface.mainWindow(), 'DAM raster Export', currentFolder)
if originalpath == '':
self.iface.messageBar().pushCritical(
'DAM raster Export',
'New layer cannot be created!'
)
return
originalname = original.name()
writingpath = originalpath + "/" + originalname + "_exported.shp"
_writer = QgsVectorFileWriter.writeAsVectorFormat(original, writingpath, 'utf-8',
driverName='ESRI Shapefile')
loadedlayer = QgsVectorLayer(writingpath, originalname + "_exported", "ogr")
QgsProject.instance().addMapLayer(loadedlayer)
self.dialog.iface.layerTreeView().setCurrentLayer(original)
except:
self.iface.messageBar().pushCritical(
'DAM raster Export',
'New layer cannot be created!'
)
self.quitDialog()
return
def rasters(self):
result = []
for row in range(self.dialog.listWidget.count()):
item = self.dialog.listWidget.item(row)
xll = item.data(PluginDialog.xllRole)
yll = item.data(PluginDialog.yllRole)
nr = item.data(PluginDialog.nrRole)
nc = item.data(PluginDialog.ncRole)
drc = item.data(PluginDialog.drcRole)
nodata = {
'ecn': self.dialog.ecnNaNBox.value(),
'pop': self.dialog.popNaNBox.value(),
}
filename = os.path.join(self.dialog.folderEdit.text(), item.text())
raster = SimpleRasterWriter(xll, yll, nr, nc, drc, item, nodata)
result.append((raster, filename))
return result
def saveRasterPropertiesNoRedraw(self):
self.saveRasterProperties(False)
def saveRasterProperties(self, redraw=True):
item = self.dialog.listWidget.currentItem()
if not item:
return
if type(self.previewLayer) != type(None):
xll = self.dialog.xllBox.value()
yll = self.dialog.yllBox.value()
dx = self.dialog.ncBox.value() * self.dialog.drcBox.value()
dy = self.dialog.nrBox.value() * self.dialog.drcBox.value()
nr = self.dialog.nrBox.value()
nc = self.dialog.ncBox.value()
layer=self.previewLayer
prov = layer.dataProvider()
# lookup index of fields using their names
xll_idx = layer.fields().lookupField('xll')
yll_idx = layer.fields().lookupField('yll')
dx_idx = layer.fields().lookupField('dx')
dy_idx = layer.fields().lookupField('dy')
nr_idx = layer.fields().lookupField('nr')
nc_idx = layer.fields().lookupField('nc')
# create a dictionary with field index as key and the attribute you want as value
atts = {xll_idx: xll, yll_idx: yll, dx_idx: dx/nc, dy_idx: dy/nr, nr_idx: nr, nc_idx: nc}
# store reference to feature you want to update
feat = layer.getFeature(self.dialog.listWidget.row(item)+1)
# call changeAttributeValues(), pass feature id and attribute dictionary
prov.changeAttributeValues({feat.id(): atts})
item.setData(PluginDialog.xllRole, xll)
item.setData(PluginDialog.yllRole, yll)
item.setData(PluginDialog.nrRole, self.dialog.nrBox.value())
item.setData(PluginDialog.ncRole, self.dialog.ncBox.value())
item.setData(PluginDialog.drcRole, self.dialog.drcBox.value())
if True:
self.dialog.rasterUpdated.emit(int(self.dialog.listWidget.row(item) + 1), self.polygon(xll, yll, dx, dy))
def quitDialog(self):
if type(self.previewLayer) != type(None):
QgsProject.instance().removeMapLayer(self.previewLayer)
self.previewLayer = None
self.act.setEnabled(True)
self.cancel = False
self.dialog.close()
def execTool(self):
"""Performs the Land Use Category export."""
input_layers = {
'ecn': {
'layer': self.dialog.ecnLayer(),
'interpol_mode': "nearest neighbor (downscaling/upscaling)", # Previously dialog box lucInterpolationMode
'nan': self.dialog.ecnNaN(),
'deltaecn': self.dialog.ecnDelta()
},
'pop': {
'layer': self.dialog.popLayer(),
'interpol_mode': "nearest neighbor (downscaling/upscaling)", # Previously dialog box lucInterpolationMode
'nan': self.dialog.popNaN(),
'pop_dam_category': self.dialog.popType(),
'pop_unittrans': self.dialog.popUnitTrans()
}
}
rasters = self.rasters() # list of tuples (raster, filename)
num_cells = sum([r.num_cells() for r, f in rasters])
if num_cells == 0:
self.quitDialog()
return
if len(rasters) > 1:
text = 'Interpolating and exporting %d rasters ...' % len(rasters)
else:
text = 'Interpolating and exporting raster ...'
progress = QProgressDialog(text, 'Abort', 0, num_cells, self.iface.mainWindow())
progress.setWindowTitle('DAM Exposure Raster Export')
progress.canceled.connect(self.scheduleAbort)
progress.show()
for raster, filename in rasters:
try:
self.export_raster(input_layers, raster, filename, progress)
except IOError:
QMessageBox.critical(self.iface.mainWindow(), 'I/O Error', 'An I/O error occured during\nraster export to file\n\n%s' % filename)
progress.close()
self.quitDialog()
return
if self.cancel:
progress.close()
self.quitDialog()
return
progress.close()
self.quitDialog()
return
def export_raster(self, input_layers, out_raster, filename, progress=None):
trans, interpol, mob_values, pop_type_values, corrected_values = dict(), dict(), dict(), dict(), dict()
for data_name, items in list(input_layers.items()):
if items['layer']:
trans[data_name] = QgsCoordinateTransform(self.previewLayer.crs(), items['layer'].crs(), QgsProject.instance()).transform
else:
trans[data_name] = lambda p: p
interpol[data_name] = RasterInterpolator(items['layer'], 1, 10, 10, items['interpol_mode'],
items['nan']).interpolate
# if the dataayer is named ecn and the tick box in the user interface is checked the ecn export will be done.
if data_name == 'ecn' and self.dialog.mGroupBox_ecn.isChecked():
rastertype_0 = 'ecn'
rastertype_1 = 'ecn_immob'
rastertype_2 = 'ecn_mob'
# Writing the standard raster file for economic immobile damages
out_raster.open(filename, input_layers, rastertype_1)
counter = 0
multiplier = 0
for i in range(int(out_raster.num_cells())):
if i == multiplier*out_raster.nc:
multiplier = multiplier + 1
counter = out_raster.num_cells()- multiplier*out_raster.nc
point = out_raster.cell_center(counter)
values = {data_name: interpol[data_name](trans[data_name](QgsPointXY(point)))}
out_raster.write_cell(values, rastertype_0)
counter = counter + 1
if progress:
progress.setValue(progress.value() + 1)
out_raster.close()
# writing a raster file as input for the mobile economic impacts.
# for that a user-chosen number is added to the land use id - by default this is 1000
if self.dialog.ecnDelta() > 0:
# ecn > 0 is a simple solution to create not mobile damage raster. The user just indicates a
# negative number or 0 for the delta and does turn off the generation of a mobile damage raster
out_raster.open(filename, input_layers, rastertype_2)
counter = 0
multiplier = 0
for i in range(int(out_raster.num_cells())):
if i == multiplier * out_raster.nc :
multiplier = multiplier + 1
counter = out_raster.num_cells()-multiplier * out_raster.nc
point = out_raster.cell_center(counter)
values = {data_name: interpol[data_name](trans[data_name](QgsPointXY(point)))}
if(values[rastertype_0] != self.dialog.ecnNaNBox.value()):
mob_values[rastertype_0] = values[rastertype_0] + input_layers[rastertype_0]['deltaecn'] # adding the user chosen value to initial immob value
out_raster.write_cell(mob_values, rastertype_0)
counter = counter + 1
if progress:
progress.setValue(progress.value() + 1)
out_raster.close()
elif data_name == 'pop' and self.dialog.mGroupBox_pop.isChecked():
rastertype_0 = 'pop'
rastertype_1 = 'pop_density'
rastertype_2 = 'pop_dam_category'
# Writing the standard raster file for population density damages; pop dens
out_raster.open(filename, input_layers, rastertype_1)
counter = 0
multiplier = 0
for i in range(int(out_raster.num_cells())):
if i == multiplier * out_raster.nc:
multiplier = multiplier + 1
counter = out_raster.num_cells()-multiplier * out_raster.nc
point = out_raster.cell_center(counter)
values = {data_name: interpol[data_name](trans[data_name](QgsPointXY(point)))}
# values multiplied with correction value entered from user. With this factor the input values are supposed to be transformed to people/m²
if values[rastertype_0] == self.dialog.popNaN():
corrected_values[rastertype_0] = values[rastertype_0]
else:
corrected_values[rastertype_0] = values[rastertype_0] * input_layers[rastertype_0]['pop_unittrans']
out_raster.write_cell_float(corrected_values, rastertype_0)
counter = counter + 1
if progress:
progress.setValue(progress.value() + 1)
out_raster.close()
# Writing the standard raster file for population density damages; pop category
# for that a user-chosen number is added to the land use id - by default this is 1000
out_raster.open(filename, input_layers, rastertype_2)
counter = 0
multiplier = 0
for i in range(int(out_raster.num_cells())):
if i == multiplier * out_raster.nc:
multiplier = multiplier + 1
counter = out_raster.num_cells()-multiplier * out_raster.nc
point = out_raster.cell_center(counter)
values = {data_name: interpol[data_name](trans[data_name](QgsPointXY(point)))}
if values[rastertype_0] == 0:
pop_type_values[rastertype_0] = 0
else:
pop_type_values[rastertype_0] = input_layers[rastertype_0][rastertype_2]
out_raster.write_cell(pop_type_values, rastertype_0)
counter = counter + 1
if progress:
progress.setValue(progress.value() + 1)
out_raster.close()
else:
continue
#######################################################################
def addRasterBounds(self, id, polygon):
if type(self.previewLayer) != type(None):
dp = self.previewLayer.dataProvider()
newPoly = QgsFeature()
newPoly.setGeometry(polygon)
dp.addFeatures([newPoly])
self.previewLayer.updateExtents()
self.previewLayer.triggerRepaint()
def updateRasterBounds(self, id, polygon):
if type(self.previewLayer) != type(None):
feat=self.previewLayer.getFeatures()
idlist=[]
for f in feat:
i=f.id()
idlist.append(i)
idlist.sort()
idtemp=idlist[id-1]
self.previewLayer.dataProvider().changeGeometryValues({idtemp: polygon})
self.previewLayer.updateExtents()
self.previewLayer.triggerRepaint()
def removeRasterBounds(self, id):
if type(self.previewLayer) != type(None):
layer = self.previewLayer
prov = layer.dataProvider()
feat=self.previewLayer.getFeatures()
idlist=[]
for f in feat:
i=f.id()
idlist.append(i)
idlist.sort()
idtemp=idlist[id-1]
f = layer.getFeature(idtemp)
xll_idx = layer.fields().lookupField('xll')
yll_idx = layer.fields().lookupField('yll')
dx_idx = layer.fields().lookupField('dx')
dy_idx = layer.fields().lookupField('dy')
nr_idx = layer.fields().lookupField('nr')
nc_idx = layer.fields().lookupField('nc')
atts = {xll_idx: 0, yll_idx: 0, dx_idx: 0, dy_idx: 0,nc_idx: 0, nr_idx: 0}
prov.changeAttributeValues({f.id(): atts})
layer.updateFields()
self.previewLayer.dataProvider().deleteFeatures([idtemp])
self.previewLayer.updateExtents()
self.previewLayer.triggerRepaint()