-
Notifications
You must be signed in to change notification settings - Fork 19
/
lecos_dlg.py
1134 lines (1011 loc) · 49.8 KB
/
lecos_dlg.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 -*-
"""
/***************************************************************************
LecoS
A QGIS plugin
Contains analytical functions for landscape analysis
-------------------
begin : 2012-09-06
copyright : (C) 2013 by Martin Jung
email : martinjung at zoho.com
***************************************************************************/
/***************************************************************************
from qgis.PyQt.QtCore import *
* *
* 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 __future__ import absolute_import
# Import PyQT bindings
from builtins import str
from builtins import range
from qgis.PyQt.QtCore import *
from qgis.PyQt.QtGui import *
from qgis.PyQt.QtWidgets import *
from qgis.core import *
# Import QGIS analysis tools
from qgis.core import *
from qgis.gui import *
#from qgis.analysis import *
# Import base libraries
import os,sys,csv,string,math,operator,subprocess,tempfile,inspect, time
from os import path
# Import functions and metrics
from . import lecos_functions as func
from . import landscape_statistics as lcs
from . import landscape_polygonoverlay as pov
from . import landscape_modifier as lmod
# Import numpy and scipy
import numpy
try:
import scipy
except ImportError:
QMessageBox.critical(QDialog(),"LecoS: Warning","Please install scipy (http://scipy.org/) in your QGIS python path.")
sys.exit(0)
from scipy import ndimage # import ndimage module seperately for easy access
# Import GDAL and ogr
try:
from osgeo import gdal
except ImportError:
import gdal
try:
from osgeo import ogr
except ImportError:
import ogr
# import Ui
from .ui.dlg_landscapestatistics import Ui_Lecos
from .ui.dlg_PolygonPerLandCover import Ui_BatchDialog
from .ui.dlg_LandscapeModifier import Ui_LandMod
tmpdir = tempfile.gettempdir()
## CODE START ##
# create the dialog controls and set up the user interface from Designer.
class LecosDialog(QDialog, Ui_Lecos):
def __init__(self, iface):
# Initialize the Dialog
QDialog.__init__( self )
self.setupUi(self)
self.iface = iface
# Get and set current pixelsize
if self.cbRaster.currentIndex() == -1:
self.sp_cellsize.setEnabled( False )
self.NoDataVal.setEnabled( False )
else:
self.sp_cellsize.setEnabled( True )
self.NoDataVal.setEnabled( True )
self.NoDataVal.setToolTip(str("Please note that the nodata value must be an integer"))
self.cellSizer( self.cbRaster.currentText() )
self.setNoData( self.cbRaster.currentText() )
#Change on Rasterfile
self.cbRaster.currentTextChanged.connect(self.cellSizer)
self.cbRaster.currentIndexChanged.connect(self.setNoData)
# Save File
self.where2Save.clicked.connect(self.selectSaveFile)
self.rbDirect.clicked.connect(self.savetoggle)
self.rbSAVE.clicked.connect(self.savetoggle)
# Change on Metric-Tabs
self.SingleMetric.currentIndexChanged.connect(self.showFunctionHelp)
self.btn_right.clicked.connect(self.switchR)
self.btn_left.clicked.connect(self.switchL)
self.SelectAll.stateChanged.connect(self.SelectAllInListL)
self.SelectAll_2.stateChanged.connect(self.SelectAllInListR)
# Button box
self.btn_About.clicked.connect(self.showAbout)
self.AcceptButton = self.bt_Accept.button( QDialogButtonBox.Ok )
self.closeButton = self.bt_Accept.button( QDialogButtonBox.Cancel )
# Manage current Raster-Layers
self.Startup()
# Shows the help for a single function
def showFunctionHelp( self, name ):
text = lcs.returnHelp(name,self.SingleMetricHelp)
# Sets the nodata value inside the field
def setNoData( self, rasterName ):
if rasterName != -1:
raster = func.getRasterLayerByName( self.cbRaster.currentText() )
rasterPath = raster.source()
raster = gdal.Open(str(rasterPath))
band = raster.GetRasterBand(1)
nodata = band.GetNoDataValue()
self.NoDataVal.setEnabled( True )
try:
self.NoDataVal.setValidator(QDoubleValidator(-999999,999999,5))
except TypeError: # Trying to catch up some strange Errors with this QT-Validator
self.NoDataVal.setValidator(QDoubleValidator(-999999,999999,5,self))
if isinstance(nodata,int)==False:
pass
#QMessageBox.warning( self, self.tr( "LecoS: Warning" ),self.tr( "Please format your rasters no-data value to integer (-99999 <-> 99999)" ) )
self.NoDataVal.setText( str(nodata) )
# Update Cellsize if a valid raster-file is selected
def cellSizer( self, rasterName ):
if rasterName != -1:
if Qgis.QGIS_VERSION_INT < 10900:
pixelSize = func.getRasterLayerByName( rasterName ).rasterUnitsPerPixel()
else:
pixelSize = func.getRasterLayerByName( rasterName ).rasterUnitsPerPixelX() # Extract The X-Value
pixelSizeY = func.getRasterLayerByName( rasterName ).rasterUnitsPerPixelY() # Extract The Y-Value
# Check for rounded equal square cellsize
if round(pixelSize,0) != round(pixelSizeY,0):
func.DisplayError(self.iface,"LecoS: Warning" ,"The cells in the layer %s are not square. Calculated values will be incorrect" % (rasterName),"WARNING")
self.sp_cellsize.setEnabled( True )
self.sp_cellsize.setValue( round( pixelSize ) )
# Save radio button
def savetoggle( self ):
if self.rbDirect.isChecked():
self.SaveCsv.setEnabled( False )
self.where2Save.setEnabled( False )
elif self.rbSAVE.isChecked():
self.SaveCsv.setEnabled( True )
self.where2Save.setEnabled( True )
# Where to save the csv
def selectSaveFile( self ):
lastUsedDir = func.lastUsedDir()
fileName, __ = QFileDialog.getSaveFileName( self, self.tr( "Save data as" ),\
lastUsedDir, "CSV files (*.csv *.CSV)" )
if len(fileName) == 0:
return
func.setLastUsedDir( fileName )
# ensure the user never ommited the extension from the file name
if not fileName.lower().endswith( ".csv" ):
fileName += ".csv"
self.SaveCsv.setText( fileName )
self.SaveCsv.setEnabled( True )
# Manage Layout and startup parameters
def Startup( self ):
# Unable unused fields
self.SaveCsv.setEnabled( False )
self.where2Save.setEnabled( False )
self.SingleMetricHelp.setEnabled( False )
# Load in raster files
self.cbRaster.addItems( func.getRasterLayersNames() )
# Display functions
self.SingleMetric.addItems( lcs.listStatistics() )
self.showFunctionHelp( self.SingleMetric.currentText() )
self.list_left.addItems( lcs.listStatistics() )
self.rlistCounter.setText( str(self.list_left.count()) )
self.rlistCounter_2.setText( str(self.list_right.count()) )
self.MetricTab.setCurrentIndex( 0 ) # Startup on single metric tab
# Switch Items on the several Metric Tab to the Right
def switchR( self ):
items = self.list_left.selectedItems()
for item in items:
n = self.list_left.row(item) # get the index/row of the item
i = self.list_left.takeItem(n) # pop
self.list_right.addItem(i) # add to right QListWidget
self.list_left.removeItemWidget( item ) # remove from left QListWidget
#update counter
self.rlistCounter.setText( str(self.list_left.count()) )
self.rlistCounter_2.setText( str(self.list_right.count()) )
# Switch Items on the several Metric Tab to the Left
def switchL( self ):
items = self.list_right.selectedItems()
for item in items:
n = self.list_right.row(item) # get the index/row of the item
i = self.list_right.takeItem(n) # pop
self.list_left.addItem(i) # add to left QListWidget
self.list_right.removeItemWidget( item ) # remove from right QListWidget
#update counter
self.rlistCounter.setText( str(self.list_left.count()) )
self.rlistCounter_2.setText( str(self.list_right.count()) )
# Select all Items in left List
def SelectAllInListL ( self, state ):
if state == Qt.Checked:
allitems = self.list_left.findItems("*", Qt.MatchWrap | Qt.MatchWildcard)
for item in allitems:
item.setSelected( True )
elif state == Qt.Unchecked:
self.list_left.clearSelection()
# Select all Items in right List
def SelectAllInListR ( self, state ):
if state == Qt.Checked:
allitems = self.list_right.findItems("*", Qt.MatchWrap | Qt.MatchWildcard)
for item in allitems:
item.setSelected( True )
elif state == Qt.Unchecked:
self.list_right.clearSelection()
# Show About Dialog
def showAbout( self ):
func.AboutDlg()
# Accept current selection and metric
def accept( self ):
# check minimal input parameters
if self.cbRaster.currentIndex() == -1:
func.DisplayError(self.iface,"LecoS: Warning" ,"Please load a classified landcover layer into Qgis first","WARNING")
return
if self.rbSAVE.isChecked():
if len(self.SaveCsv.text()) == 0:
func.DisplayError(self.iface,"LecoS: Warning" ,"Please select where to save the results","WARNING")
return
if path.exists(self.SaveCsv.text()):
func.DisplayError(self.iface,"LecoS: Warning" ,"File already exisits. Please select another path or delete file","WARNING")
return
if self.sp_cellsize.value() == 0:
func.DisplayError(self.iface,"LecoS: Warning" ,"Please entry a correct cellsize (greater zero)","WARNING")
return
# Values and Preset
self.progressBar.setRange( 0, 4)
self.progressBar.setValue( 0 ) # pb start
raster = func.getRasterLayerByName( self.cbRaster.currentText() )
rasterPath = raster.source()
dataPath = self.SaveCsv.text()
cellsize = self.sp_cellsize.value()
try:
nodata = float(self.NoDataVal.text())
except ValueError:
func.DisplayError(self.iface,"LecoS: Warning" ,"Please set a correct nodata-value","WARNING")
return
## Calculate Single Metric
what = self.MetricTab.currentIndex()
# Single
if(what == 0):
if len(self.SingleMetric.currentText()) >= 5:
classes, array = lcs.f_landcover(rasterPath,nodata)
self.progressBar.setValue( self.progressBar.value() + 1 )
# Looping through all classes
res = []
res_tit = ["Class"]
cl_analys = lcs.LandCoverAnalysis(array,cellsize,classes)
for cl in classes:
cl_array = numpy.copy(array) # new working array
cl_array[cl_array!=cl] = 0
cl_analys.f_ccl(cl_array) # CC-labeling
name, result = cl_analys.execSingleMetric(self.SingleMetric.currentText(),cl) # Returns values for all
self.progressBar.setValue( self.progressBar.value() + 1 )
# Append Values to result class and table name array
r = [cl, result]
if len(res) == 0:
res.append(r)
else:
no_class_in_array = True
for id, item in enumerate(res):
if item[0] == cl:
res[id].append(result)
no_class_in_array = False
if no_class_in_array:
res.append(r)
if res_tit.count(name) == 0:
res_tit.append(name)
else:
func.DisplayError(self.iface,"LecoS: Warning" ,"Please select a valid single metric","WARNING")
## Several Metrics
elif(what == 1):
metrics = []
allitems = self.list_right.findItems("*", Qt.MatchWrap | Qt.MatchWildcard)
if len(allitems)==0:
func.DisplayError(self.iface,"LecoS: Warning" ,"Please select at least one item from the left list","WARNING")
return
for item in allitems:
metrics.append(str(item.text()))
classes, array = lcs.f_landcover(rasterPath,nodata)
self.progressBar.setValue( self.progressBar.value() + 1 )
# Looping through all classes
res = []
res_tit = ["Class"]
cl_analys = lcs.LandCoverAnalysis(array,cellsize,classes)
for m in metrics:
for cl in classes:
cl_array = numpy.copy(array) # new working array
cl_array[cl_array!=cl] = 0
cl_analys.f_ccl(cl_array) # CC-Labeling
name, result = cl_analys.execSingleMetric(m,cl)
self.progressBar.setValue( self.progressBar.value() + 1 )
# Append Values to result class and table name array
r = [cl, result]
if len(res) == 0:
res.append(r)
else:
no_class_in_array = True
for id, item in enumerate(res):
if item[0] == cl:
res[id].append(result)
no_class_in_array = False
if no_class_in_array:
res.append(r)
if res_tit.count(name) == 0:
res_tit.append(name)
self.iface.mainWindow().statusBar().showMessage("Metric %s calculated" % (m))
## Landscape Metrics
elif what == 2:
metrics = []
if self.ch_LC1.isChecked():
metrics.append("LC_Mean")
if self.ch_LC2.isChecked():
metrics.append("LC_Sum")
if self.ch_LC3.isChecked():
metrics.append("LC_Min")
if self.ch_LC4.isChecked():
metrics.append("LC_Max")
if self.ch_LC5.isChecked():
metrics.append("LC_SD")
if self.ch_LC6.isChecked():
metrics.append("LC_LQua")
if self.ch_LC7.isChecked():
metrics.append("LC_Med")
if self.ch_LC8.isChecked():
metrics.append("LC_UQua")
if self.ch_div1.isChecked():
metrics.append("DIV_SH")
if self.ch_div2.isChecked():
metrics.append("DIV_EV")
if self.ch_div3.isChecked():
metrics.append("DIV_SI")
if len(metrics)==0:
func.DisplayError(self.iface,"LecoS: Warning" ,"Please select at least one item","WARNING")
return
# Processing
try:
int(nodata)
except ValueError as TypeError:
func.DisplayError(self.iface,"LecoS: Warning" ,"Please classify your raster with a correct integer nodata value","WARNING")
return
classes, array = lcs.f_landcover(rasterPath,nodata) # Get classes and value
self.progressBar.setValue( self.progressBar.value() + 1 )
# Looping through the selected metrics
res = []
res_tit = ["Metric","Value"]
cl_analys = lcs.LandCoverAnalysis(array,cellsize,classes)
for m in metrics:
name, result = cl_analys.execLandMetric(m,nodata)
self.progressBar.setValue( self.progressBar.value() + 1 )
# Append Values to result class array
res.append([name, result])
self.iface.mainWindow().statusBar().showMessage("Metric %s calculated" % (m))
self.progressBar.setValue( self.progressBar.value() + 1 )
# Write results
if self.rbSAVE.isChecked():
func.DisplayError(self.iface,"LecoS: Info" ,"Results were successfully saved to file!","INFO")
func.saveToCSV(res,res_tit,dataPath)
else:
func.DisplayError(self.iface,"LecoS: Info" ,"Calculations finished!","INFO")
func.ShowResultTableDialog(res_tit, res)
self.progressBar.setValue( self.progressBar.value() + 1 )
self.close()
# Gui for batch computing Landcover for vector features
class BatchDialog(QDialog, Ui_BatchDialog):
def __init__(self, iface):
# Initialize the Dialog
QDialog.__init__( self )
self.setupUi(self)
self.iface = iface
# Connects
self.ch_selectAll.stateChanged.connect(self.SelectAllInList)
self.locateDir.clicked.connect(self.selectSaveFile)
self.cb_Raster.currentIndexChanged.connect(self.EnableStuff) # Enable Stuff
self.cb_Raster.currentIndexChanged.connect(self.loadIDFields) # Load IDFields
self.cb_Raster.currentIndexChanged.connect(self.ListMetrics) # Change Class metrics
self.cb_LClass.currentIndexChanged.connect(self.vectorClass) # Get Vector layers class values
# Enable Stuff
self.cb_Raster.currentIndexChanged.connect(self.EnableStuff) # Landscape
self.cb_Vector.currentIndexChanged.connect(self.EnableStuff) # Poly overlay
self.rb_Landscape.clicked.connect(self.EnableStuff) # Change available stuff
self.rb_Class.clicked.connect(self.EnableStuff) # Change available stuff
self.ch_saveResult.stateChanged.connect(self.EnableStuff) # Change output
# Button box
#self.AcceptButton = self.startButtons.button( QDialogButtonBox.Ok )
self.AcceptButton = self.startButtons.button( QDialogButtonBox.Ok )
self.closeButton = self.startButtons.button( QDialogButtonBox.Cancel )
#QObject.connect( self.AcceptButton, SIGNAL( "clicked()" ), self.go )
#self.closeButton = self.startButtons.button( QDialogButtonBox.Cancel )
self.btn_About.clicked.connect(self.showAbout)
#Startup
self.startup()
# Startup function
def startup(self):
# Load in landscape and vector files
vec = func.getVectorLayersNames()
ras = func.getRasterLayersNames()
self.cb_Raster.addItems( ras + vec )
self.cb_Vector.addItems( [""] + vec )
self.ListMetrics()
# Unable most features
self.EnableStuff("default")
# Load Class metrics
def ListMetrics(self,ind=""):
self.Cl_Metrics.clear()
curLay = func.getLayerByName( self.cb_Raster.currentText() )
if type(curLay) == QgsRasterLayer:
stats = lcs.listStatistics()
self.Cl_Metrics.addItems(stats)
elif type(curLay) == QgsVectorLayer:
stats = pov.listVectorStatistics()
self.Cl_Metrics.addItems(stats)
# Enable all necessary functions
def EnableStuff(self,what=""):
if what != "default":
ras = func.getLayerByName( what )
vec = func.getVectorLayerByName( what )
land = self.cb_Raster.currentText() == what
if self.rb_Class.isChecked(): # Check if Landscape or Class structures should be computed
self.cb_LClass.setEnabled( True )
# Disable General methods
self.ch_LC1.setEnabled( False ),self.ch_LC2.setEnabled( False ),self.ch_LC3.setEnabled( False ),self.ch_LC4.setEnabled( False ),self.ch_LC5.setEnabled( False ),self.ch_LC6.setEnabled( False ),self.ch_LC7.setEnabled( False ),self.ch_LC8.setEnabled( False )
# Disable Diversity methods
self.ch_div1.setEnabled( False ),self.ch_div2.setEnabled( False ),self.ch_div3.setEnabled( False )
# Set unchecked
self.ch_LC1.setChecked( False ),self.ch_LC2.setChecked( False ),self.ch_LC3.setChecked( False ),self.ch_LC4.setChecked( False ),self.ch_LC5.setChecked( False ),self.ch_LC6.setChecked( False ),self.ch_LC7.setChecked( False ),self.ch_LC8.setChecked( False )
# Disable Diversity methods
self.ch_div1.setChecked( False ),self.ch_div2.setChecked( False ),self.ch_div3.setChecked( False )
# Enable Class metrics
self.Cl_Metrics.setEnabled( True )
self.ch_selectAll.setEnabled( True )
elif self.rb_Landscape.isChecked():
# Enable General methods
self.ch_LC1.setEnabled( True ),self.ch_LC2.setEnabled( True ),self.ch_LC3.setEnabled( True ),self.ch_LC4.setEnabled( True ),self.ch_LC5.setEnabled( True ),self.ch_LC6.setEnabled( True ),self.ch_LC7.setEnabled( True ),self.ch_LC8.setEnabled( True )
# Disable Diversity methods
self.ch_div1.setEnabled( True ),self.ch_div2.setEnabled( True ),self.ch_div3.setEnabled( True )
self.cb_LClass.setEnabled( False )
# Enable Class metrics
self.Cl_Metrics.setEnabled( False )
self.ch_selectAll.setEnabled( False )
# Clear classes
self.cb_LClass.clear()
# TODO: Vector grid overlay
# Disable vector grid overlay field
if type(ras) == QgsVectorLayer and land:
if self.ClassLayout.count() != 3:
self.VCl = QComboBox()
self.VCl.setEnabled( False )
self.ClassLayout.insertWidget(2,self.VCl)
self.cb_Vector.setEnabled( False )
self.cb_Vector.setCurrentIndex(0)
self.cb_SelD.setEnabled( True )
self.loadIDFields()
self.ch_addToTable.setEnabled( False ) # Disable add to attribute table for inherent vector layers
self.ch_addToTable.setChecked( False )
if self.rb_Landscape.isChecked():
self.ch_div1.setEnabled( False ),self.ch_div2.setEnabled( False ),self.ch_div3.setEnabled( False )
elif (type(ras) == QgsRasterLayer) and land:
# Delete Class Vector widget if available
if self.ClassLayout.count() == 3:
self.VCl.hide()
self.ClassLayout.removeWidget(self.VCl)
self.cb_Vector.setEnabled( True )
#self.cb_SelD.setEnabled( False )
self.ch_addToTable.setEnabled( True )
if self.rb_Landscape.isChecked():
self.ch_div1.setEnabled( True ),self.ch_div2.setEnabled( True ),self.ch_div3.setEnabled( True )
else:
self.ch_div1.setEnabled( False ),self.ch_div2.setEnabled( False ),self.ch_div3.setEnabled( False )
# Enable and load classes
curLay = func.getLayerByName( self.cb_Raster.currentText() )
if type(ras) == QgsRasterLayer or type(curLay) == QgsRasterLayer:
if self.rb_Class.isChecked():
self.cb_LClass.setEnabled( True )
self.loadClasses("ras") # load classes
elif type(ras) == QgsVectorLayer or type(curLay) == QgsVectorLayer:
if self.rb_Class.isChecked():
self.cb_LClass.setEnabled( True )
self.loadClasses("vec") # load classes
self.loadIDFields() # load ID fields
# Enable ID field for vector overlay
vecOV = func.getVectorLayerByName( self.cb_Vector.currentText() )
if type(curLay) == QgsRasterLayer:
if type(vecOV) == QgsVectorLayer and vecOV != "":
self.cb_SelD.setEnabled( True )
self.loadIDFields()
else:
self.cb_SelD.setEnabled( False )
self.cb_SelD.clear()
# Check Status of output
if self.ch_saveResult.isChecked():
self.where2Save.setEnabled( True )
self.locateDir.setEnabled( True )
else:
self.where2Save.setEnabled( False )
self.locateDir.setEnabled( False )
else:
self.Cl_Metrics.setEnabled( False )
self.ch_selectAll.setEnabled( False )
self.cb_LClass.setEnabled( False )
self.cb_SelD.setEnabled( False )
# Load ID fields
def loadIDFields(self):
vectorName = func.getLayerByName( self.cb_Raster.currentText() )
vectorLayer = func.getVectorLayerByName( self.cb_Vector.currentText() )
if (vectorLayer is None): return
if vectorLayer != "" and type(vectorName) == QgsVectorLayer:
self.cb_SelD.setEnabled( True )
self.cb_SelD.clear()
fields = func.getFieldList( vectorName )
if Qgis.QGIS_VERSION_INT >= 10900:
for field in fields:
if field.type() in [ QVariant.Int, QVariant.String ]:
self.cb_SelD.addItem( field.name() )
else:
prov = vectorName.dataProvider()
for k, field in list(prov.items()):
if field.type() in [ QVariant.Int, QVariant.String ]:
self.cb_SelD.addItem( field.name() )
else: # RasterLayer is current layer
self.cb_SelD.setEnabled( True )
self.cb_SelD.clear()
# Load Grouping ID for vector field and table output
fields = func.getFieldList( vectorLayer )
for field in fields:
self.cb_SelD.addItem( field.name() )
# Get landscape classes
def loadClasses(self,typ):
if typ == "ras":
rasterName = func.getRasterLayerByName( self.cb_Raster.currentText() )
if rasterName != "":
rasterPath = rasterName.source()
raster = gdal.Open(str(rasterPath))
band = raster.GetRasterBand(1)
nodata = band.GetNoDataValue()
array = band.ReadAsArray()
self.classes = sorted(numpy.unique(array)) # get array of classes
try:
self.classes.remove(nodata) # Remove nodata-values from classes array
except ValueError:
try:
self.classes.remove(0)
except ValueError:
pass
classes = [str(numeric_cl) for numeric_cl in self.classes]
self.cb_LClass.clear()
self.cb_LClass.addItems( classes )
else:
self.cb_LClass.clear()
self.cb_LClass.addItems( [""] )
elif typ == "vec":
vectorName = func.getVectorLayerByName( self.cb_Raster.currentText() )
if vectorName != "":
self.cb_LClass.clear()
fields = func.getFieldList( vectorName )
self.classes = []
if Qgis.QGIS_VERSION_INT >= 10900:
for field in fields:
if field.type() in [ QVariant.Int, QVariant.Double, QVariant.String ]:
self.cb_LClass.addItem( field.name() )
self.classes.append(field.name())
else:
prov = vectorName.dataProvider()
for k, field in list(prov.items()):
if field.type() in [ QVariant.Int, QVariant.Double, QVariant.String ]:
self.cb_LClass.addItem( field.name() )
self.classes.append(field.name())
else:
self.cb_LClass.clear()
# Load Vector classes from attribute table
def vectorClass(self,cl):
vectorName = func.getLayerByName( self.cb_Raster.currentText() )
if type(vectorName) == QgsVectorLayer:
cur = str(self.cb_LClass.currentText())
if cur != "":
self.VCl.clear()
self.VCl.setEnabled( True )
attr = func.getAttributeList(vectorName,cur)
self.VecAttr = []
for field in attr:
self.VCl.addItem( str(field) )
self.VecAttr.append(field)
# Select all Class metrics
def SelectAllInList(self, state):
if state == Qt.Checked:
allitems = self.Cl_Metrics.findItems("*", Qt.MatchWrap | Qt.MatchWildcard)
for item in allitems:
item.setSelected( True )
self.ch_selectAll.setText("Unselect all")
elif state == Qt.Unchecked:
self.Cl_Metrics.clearSelection()
self.ch_selectAll.setText("Select all")
# Where to save the csv
def selectSaveFile( self ):
lastUsedDir = func.lastUsedDir()
fileName, __ = QFileDialog.getSaveFileName( self, self.tr( "Save data as" ),\
lastUsedDir, "CSV files (*.csv *.CSV)" )
if len(fileName) < 1:
return
func.setLastUsedDir( fileName )
# ensure the user never ommited the extension from the file name
if not fileName.lower().endswith( ".csv" ):
fileName += ".csv"
self.where2Save.setText( fileName )
self.where2Save.setEnabled( True )
# # Show feature count
# def featureCount(self, vectorName):
# if vectorName != "":
# # Load vector data
# self.vector = func.getVectorLayerByName( self.cb_Vector.currentText() )
# self.vectorPath = self.vector.source()
# nf = self.vector.featureCount()
# self.lab_feat.setText("Features ("+str(nf)+")")
# else:
# self.lab_feat.setText("Features (0)")
# Show About Dialog
def showAbout( self ):
func.AboutDlg()
# Returns the selected metrics
def getSelMetric(self):
res = []
m = self.Cl_Metrics.selectedItems()
for item in m:
res.append(str( item.text() ))
# Other Metrics ?
if self.ch_LC1.isChecked():
res.append("LC_Mean")
if self.ch_LC2.isChecked():
res.append("LC_Sum")
if self.ch_LC3.isChecked():
res.append("LC_Min")
if self.ch_LC4.isChecked():
res.append("LC_Max")
if self.ch_LC5.isChecked():
res.append("LC_SD")
if self.ch_LC6.isChecked():
res.append("LC_LQua")
if self.ch_LC7.isChecked():
res.append("LC_Med")
if self.ch_LC8.isChecked():
res.append("LC_UQua")
if self.ch_div1.isChecked():
res.append("DIV_SH")
if self.ch_div2.isChecked():
res.append("DIV_EV")
if self.ch_div3.isChecked():
res.append("DIV_SI")
return res
# Runs the routine
def accept(self):
# Error catching and variable returning
if self.cb_Raster.currentIndex() == -1:
func.DisplayError(self.iface,"LecoS: Warning" ,"Please load and select a classified landscape layer first","WARNING")
return
self.landscape = func.getLayerByName( self.cb_Raster.currentText() )
self.landPath = self.landscape.source()
if type(self.landscape) == QgsVectorLayer: # Check if landscape vector layer is a polygon
if self.landscape.geometryType() != qgis.core.QgsWkbTypes.PolygonGeometry:
func.DisplayError(self.iface,"LecoS: Warning" ,"The landscape layer have to be of geometry type: Polygons","WARNING")
return
# Default values
self.vector = None
self.vectorPath = None
# Load in overlaying Grid and raise error if not a polygon or no landscape raster
if self.cb_Vector.currentText() != "":
self.vector = func.getVectorLayerByName( self.cb_Vector.currentText() )
self.vectorPath = self.vector.source()
if type(self.landscape) == QgsVectorLayer:
if self.landscape.geometryType() != qgis.core.QgsWkbTypes.PolygonGeometry:
func.DisplayError(self.iface,"LecoS: Warning" ,"This tool need the vector grid to have the geometry type: Polygon","WARNING")
return
# Check if both layers have the same projection
cr1 = self.vector.crs()
cr2 = self.landscape.crs()
if cr1!=cr2:
func.DisplayError(self.iface,"LecoS: Warning" ,"Please make sure that both layers have the same spatial projection","WARNING")
return
# Check if a layer has been chosen twice
if self.landPath == self.vectorPath:
func.DisplayError(self.iface,"LecoS: Warning" ,"It is not possible to overlay layers from the same source. Specify a Grouping ID","WARNING")
return
elif type(self.landscape) == QgsRasterLayer:
func.DisplayError(self.iface,"LecoS: Warning" ,"Please load and select an overlaying vector grid","WARNING")
return
elif type(self.landscape) == QgsVectorLayer:
if self.cb_SelD.currentText() == "":
func.DisplayError(self.iface,"LecoS: Warning" ,"You didn't choose an overlaying vector grid and therefore need to specify a grouping ID","WARNING")
return
if self.rb_Landscape.isChecked(): # Landscape or Class metrics
self.cl_metric = False
self.classIND = None
else:
self.cl_metric = True
self.classIND = self.cb_LClass.currentText()
# The ID
self.LandID = self.cb_SelD.currentText()
self.metrics = self.getSelMetric() # Get list of all Metrics
if len(self.metrics) == 0:
func.DisplayError(self.iface,"LecoS: Warning" ,"Please select at least one metric to compute!","WARNING")
return
if self.ch_saveResult.isChecked():
self.FileSave = True
self.FileSavePath = self.where2Save.text()
# If no output has been defined -> create a temporary file
if self.FileSavePath == "Select a destination or leave blank to create a temporary file":
self.FileSavePath = tmpdir+os.path.sep+"temp_"+str(self.cb_Raster.currentText())+"_"+str(int(time.time()))+"_results.csv"
else:
self.FileSave = False
if self.ch_addToTable.isChecked(): # Add to Attribute Table
self.Add2Table = True
else:
self.Add2Table = False
## Processing Start
### Vector part
if type(self.landscape) == QgsVectorLayer:
if self.cb_Vector.currentText() == "":
# Use inherent vector grouping id
#self.classIND
if self.cl_metric:
# Analysis with a given vector class field
if(self.classIND == ""):
func.DisplayError(self.iface,"LecoS: Warning" ,"Please select a valid landcover class!","WARNING")
return
else:
clf = self.classes[self.cb_LClass.currentIndex()] # Get selected classField
bat = pov.VectorBatchConverter(self.landscape,self.LandID,clf,self.iface)
cl = self.VecAttr[self.VCl.currentIndex()] # Get selected class in field
results = []
for cmd in self.metrics:
results.append(bat.go(cmd,cl))
self.iface.mainWindow().statusBar().showMessage("Metric %s calculated" % (cmd))
self.Output(results)
else:
# Vector analysis on Landscape Level
bat = pov.VectorBatchConverter(self.landscape,self.LandID)
results = []
for el in ('LC','DIV'):
met = [x for x in self.metrics if el in x]
for cmd in met:
results.append(bat.go(cmd))
self.iface.mainWindow().statusBar().showMessage("Metric %s calculated" % (cmd))
self.Output(results)
else:
# Use overlaying vector grid -> need to cut landscape vectors first
#TODO: vector grid overlay
pass
### Raster part
if type(self.landscape) == QgsRasterLayer:
# Get None Nulldata Error
try:
image = gdal.Open(str(self.landPath))
band = image.GetRasterBand(1)
nd = band.GetNoDataValue()
int(nd)
except TypeError as ValueError:
func.DisplayError(self.iface,"LecoS: Warning" ,"Please classify your raster with a correct nodata value","WARNING")
return
# Check if polygon is correctly set
try:
v = ogr.Open(str( self.vectorPath ))
l = v.GetLayer()
l.GetFeature(0).GetGeometryRef()
except AttributeError:
func.DisplayError(self.iface,"LecoS: Warning" ,"There is something wrong with your polygon layer. Try to save it to a new file.","WARNING")
return
# Look for smaller rasters than polygons
rasE = self.landscape.extent()
# vecE = self.vector.extent()
# if vecE > rasE:
# func.DisplayError(self.iface,"LecoS: Warning" ,"Please cut the overlaying vector to the rasters extent","WARNING")
# return
bat = pov.BatchConverter(self.landPath,self.vectorPath,self.iface)
# Landscape or classified
if self.cl_metric:
if(self.classIND == ""):
func.DisplayError(self.iface,"LecoS: Warning" ,"Please select a valid landcover class!","WARNING")
return
else:
cl = int(self.classes[self.cb_LClass.currentIndex()]) # Get selected class
if Qgis.QGIS_VERSION_INT < 10900:
cellsize = self.landscape.rasterUnitsPerPixel()
else:
cellsize = self.landscape.rasterUnitsPerPixelX() # Extract The X-Value
cellsizeY = self.landscape.rasterUnitsPerPixelY() # Extract The Y-Value
# Check for rounded equal square cellsize
if round(cellsize,0) != round(cellsizeY,0):
func.DisplayError(self.iface,"LecoS: Warning" ,"The cells in the layer %s are not square. Calculated values will be incorrect" % (self.cb_Raster.currentText()),"WARNING")
#Calculate selected statistics for classified raster
results = []
error = 0
for cmd in self.metrics:
err, r = bat.go(cmd,cl,cellsize,None,rasE)
results.append(r)
error = error + len(err)
self.DLmessagebar(error,err)
self.Output(results)
else:
if Qgis.QGIS_VERSION_INT < 10900:
cellsize = self.landscape.rasterUnitsPerPixel()
else:
cellsize = self.landscape.rasterUnitsPerPixelX() # Extract The X-Value
cellsizeY = self.landscape.rasterUnitsPerPixelY() # Extract The Y-Value
# Check for rounded equal square cellsize
if round(cellsize,0) != round(cellsizeY,0):
func.DisplayError(self.iface,"LecoS: Warning" ,"The cells in the layer %s are not square. Calculated values will be incorrect" % (self.cb_Raster.currentText()),"WARNING")
#Calculate statistics for unclassified raster
results = []
error = 0
for el in ('LC','DIV'):
met = [x for x in self.metrics if el in x]
for cmd in met:
err, r = bat.go(cmd,None,cellsize,None,rasE)
results.append(r)
error = error + len(err)
self.DLmessagebar(error,err)
self.Output(results)
# Dialog for to messagebar
def DLmessagebar(self,n,err):
if n > 0 and Qgis.QGIS_VERSION_INT >= 10900:
error = str(n / len(self.metrics))
text = "There were no overlay values for "+error+" vector features. All features unable to compute are selected now for inspectation."
widget = self.iface.messageBar().createMessage("LecoS - Warning",text)
# Combobox for selecting. Not found entries selected
#btn = QComboBox()
#QObject.connect( btn, SIGNAL( "currentIndexChanged( QString )" ), self.selectFeatID )
#widget.layout().addWidget(btn)
#self.iface.messageBar().pushWidget(widget, QgsMessageBar.WARNING)
#for item in err:
# btn.addItem(str(item))
#return btn
for item in err:
self.selectFeatID(item)
# Select features with ID
def selectFeatID(self,ID):
ID = int(ID)
self.vector.select(ID)
# Function for Output generation
def Output(self,results):
if self.Add2Table:
# Add to overlaying vector grid
add = func.addAttributesToLayer(self.vector,results)
if add == False:
func.DisplayError(self.iface,"LecoS: Warning" ,"Values couldn't be added to the attribute table","WARNING")
else:
func.DisplayError(self.iface,"LecoS: Info" ,"Values were added to the vector layers attribute table","INFO")
if self.FileSave:
# Write to file
if type(self.landscape) == QgsVectorLayer:
title = ["GroupingField"]
else:
title = ["PolygonFeatureID"]
# Add grouping ID if selected
if self.LandID != "" or None:
title.append(str(self.LandID))
for x in results:
try: # Catch in case there are no results
title.append( str(x[0][1]) )
except IndexError:
func.DisplayError(self.iface,"LecoS: Warning" ,"Results couldn't be calculated. Please make sure all shapes are within the rasters extent!","WARNING")
return
f = open(self.FileSavePath, "w", newline='' )
writer = csv.writer(f,delimiter=';',quotechar="",quoting=csv.QUOTE_NONE)
writer.writerow(title)
# Get values of Overlay grouping ID
if type(self.landscape) == QgsRasterLayer:
if self.LandID != "" or None:
attr = func.getAttributeList(self.vector,self.LandID)
# Get number of polygon features
feat = list(range(0,len(results[0])))
for feature in feat: # Write feature to new line
if type(self.landscape) == QgsVectorLayer:
r = [results[0][feature][0]]
else:
r = [feature]
# Add Grouping Field value
if self.LandID != "" or None:
r.append(attr[feature])
for item in results:
r.append(item[feature][2])
writer.writerow(r)
f.close()
func.DisplayError(self.iface,"LecoS: Info" ,"Landcover statistics were successfully written to file","INFO")
if (self.Add2Table == False) and (self.FileSave == False):
# Direct Output?
if type(self.landscape) == QgsVectorLayer:
title = ["GroupingField"]
else:
title = ["PolygonFeatureID"]
for x in results:
title.append( str(x[0][1]) )
w = func.ShowResultTableDialog2(title,results)
if w: