/
doGeoprocessing.py
1645 lines (1558 loc) · 63.3 KB
/
doGeoprocessing.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 -*-
#-----------------------------------------------------------
#
# fTools
# Copyright (C) 2008-2011 Carson Farmer
# EMAIL: carson.farmer (at) gmail.com
# WEB : http://www.ftools.ca/fTools.html
#
# A collection of data management and analysis tools for vector data
#
# Geoprocessing functions adapted from 'Geoprocessing Plugin',
# (C) 2008 by Dr. Horst Duester, Stefan Ziegler
#-----------------------------------------------------------
#
# licensed under the terms of GNU GPL 2
#
# 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.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
#---------------------------------------------------------------------
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from qgis.core import *
from qgis.gui import *
from ui_frmGeoprocessing import Ui_Dialog
import ftools_utils
import sys
class GeoprocessingDialog( QDialog, Ui_Dialog ):
def __init__( self, iface, function ):
QDialog.__init__( self, iface.mainWindow() )
self.iface = iface
self.setupUi( self )
self.param.setValidator(QDoubleValidator(self.param))
self.myFunction = function
QObject.connect( self.btnBrowse, SIGNAL( "clicked()" ), self.outFile )
QObject.connect( self.inShapeA, SIGNAL( "currentIndexChanged(QString)" ), self.checkA )
QObject.connect( self.inShapeB, SIGNAL( "currentIndexChanged(QString)" ), self.checkB )
if function == 4 or function == 1 or function == 2:
QObject.connect( self.inShapeA, SIGNAL( "currentIndexChanged(QString)" ), self.update )
self.manageGui()
self.success = False
self.cancel_close = self.buttonBox_2.button( QDialogButtonBox.Close )
self.buttonOk = self.buttonBox_2.button( QDialogButtonBox.Ok )
self.progressBar.setValue (0 )
def checkA( self ):
inputLayer = unicode( self.inShapeA.currentText() )
if inputLayer != "":
changedLayer = ftools_utils.getVectorLayerByName( inputLayer )
if changedLayer.selectedFeatureCount() != 0:
self.useSelectedA.setCheckState( Qt.Checked )
else:
self.useSelectedA.setCheckState( Qt.Unchecked )
def checkB( self ):
inputLayer = unicode( self.inShapeB.currentText() )
if inputLayer != "":
changedLayer = ftools_utils.getVectorLayerByName( inputLayer )
if changedLayer.selectedFeatureCount() != 0:
self.useSelectedB.setCheckState( Qt.Checked )
else:
self.useSelectedB.setCheckState( Qt.Unchecked )
def update( self ):
self.attrib.clear()
inputLayer = unicode( self.inShapeA.currentText() )
if inputLayer != "":
changedLayer = ftools_utils.getVectorLayerByName( inputLayer )
changedField = changedLayer.dataProvider().fields()
for f in changedField:
self.attrib.addItem( unicode( f.name() ) )
if self.myFunction == 4:
self.attrib.addItem( "--- " + self.tr( "Dissolve all" ) + " ---" )
def accept( self ):
if self.inShapeA.currentText() == "":
QMessageBox.warning( self, self.tr("Geoprocessing"), self.tr( "Please specify an input layer" ) )
elif self.inShapeB.isVisible() and self.inShapeB.currentText() == "":
QMessageBox.warning( self, self.tr("Geoprocessing"), self.tr( "Please specify a difference/intersect/union layer" ) )
elif self.param.isEnabled() and self.param.isVisible() and self.param.text() == "":
QMessageBox.warning( self, self.tr("Geoprocessing"), self.tr( "Please specify valid buffer value" ) )
elif self.attrib.isEnabled() and self.attrib.isVisible() and self.attrib.currentText() == "":
QMessageBox.warning( self, self.tr("Geoprocessing"), self.tr( "Please specify dissolve field" ) )
elif self.outShape.text() == "":
QMessageBox.warning( self, self.tr("Geoprocessing"), self.tr( "Please specify output shapefile" ) )
else:
changedLayerA = ftools_utils.getVectorLayerByName( self.inShapeA.currentText() )
changedLayerB = ftools_utils.getVectorLayerByName( self.inShapeB.currentText() )
# check for selection in layer A
if self.useSelectedA.isChecked() and changedLayerA.selectedFeatureCount() == 0:
QMessageBox.warning( self, self.tr("Geoprocessing"), self.tr( "No features selected, please uncheck 'Use selected' or make a selection" ) )
# check for selection in layer B
elif self.inShapeB.isVisible() and self.useSelectedB.isChecked() and changedLayerB.selectedFeatureCount() == 0:
QMessageBox.warning( self, self.tr("Geoprocessing"), self.tr( "No features selected, please uncheck 'Use selected' or make a selection" ) )
else:
self.outShape.clear()
if self.attrib.isEnabled():
self.geoprocessing( self.inShapeA.currentText(), self.inShapeB.currentText(),
unicode( self.attrib.currentText() ), self.mergeOutput.checkState(), self.useSelectedA.checkState(),
self.useSelectedB.checkState(), self.spnSegments.value() )
else:
if self.param.isEnabled() and self.param.isVisible():
parameter = float( self.param.text() )
else:
parameter = None
self.geoprocessing( self.inShapeA.currentText(), self.inShapeB.currentText(),
parameter, self.mergeOutput.checkState(), self.useSelectedA.checkState(), self.useSelectedB.checkState(), self.spnSegments.value() )
def outFile( self ):
self.outShape.clear()
( self.shapefileName, self.encoding ) = ftools_utils.saveDialog( self )
if self.shapefileName is None or self.encoding is None:
return
self.outShape.setText( self.shapefileName )
def manageGui( self ):
if self.myFunction == 1: # Buffer
self.label_2.hide()
self.inShapeB.hide()
self.useSelectedB.hide()
self.label_4.hide()
self.setWindowTitle( self.tr( "Buffer(s)" ) )
elif self.myFunction == 2: # Convex hull
self.label_2.hide()
self.inShapeB.hide()
self.useSelectedB.hide()
self.rdoBuffer.setText( self.tr( "Create single minimum convex hull" ) )
self.rdoField.setText( self.tr( "Create convex hulls based on input field" ) )
self.label_4.hide()
self.param.hide()
self.lblSegments.hide()
self.spnSegments.hide()
self.setWindowTitle( self.tr( "Convex hull(s)" ) )
self.mergeOutput.hide()
elif self.myFunction == 4: # Dissolve
self.label_2.hide()
self.inShapeB.hide()
self.useSelectedB.hide()
self.rdoBuffer.hide()
self.attrib.setEnabled( True )
self.param.hide()
self.rdoField.hide()
self.mergeOutput.hide()
self.lblSegments.hide()
self.spnSegments.hide()
self.setWindowTitle( self.tr( "Dissolve" ) )
else:
self.rdoBuffer.hide()
self.param.hide()
self.label_4.hide()
self.rdoField.hide()
self.attrib.hide()
self.mergeOutput.hide()
self.lblSegments.hide()
self.spnSegments.hide()
if self.myFunction == 3: # Difference
self.label_2.setText( self.tr( "Difference layer" ) )
self.setWindowTitle( self.tr( "Difference" ) )
elif self.myFunction == 5: # Intersect
self.label_2.setText( self.tr( "Intersect layer" ) )
self.setWindowTitle( self.tr( "Intersect" ) )
elif self.myFunction == 7: # Symetrical difference
self.label_2.setText( self.tr( "Difference layer" ) )
self.setWindowTitle( self.tr( "Symetrical difference" ) )
self.useSelectedA.hide()
self.useSelectedB.hide()
elif self.myFunction == 8: # Clip
self.label_2.setText( self.tr( "Clip layer" ) )
self.setWindowTitle( self.tr( "Clip" ) )
else: # Union
self.label_2.setText( self.tr( "Union layer" ) )
self.setWindowTitle( self.tr( "Union" ) )
self.useSelectedA.hide()
self.useSelectedB.hide()
self.resize(381, 100)
self.populateLayers()
def populateLayers( self ):
myListA = []
myListB = []
self.inShapeA.clear()
self.inShapeB.clear()
if self.myFunction == 4:
myListA = ftools_utils.getLayerNames( [ QGis.Line, QGis.Polygon ] )
myListB = []
else:
myListA = ftools_utils.getLayerNames( [ QGis.Point, QGis.Line, QGis.Polygon ] )
myListB = ftools_utils.getLayerNames( [ QGis.Point, QGis.Line, QGis.Polygon ] )
self.inShapeA.addItems( myListA )
self.inShapeB.addItems( myListB )
#1: Buffer
#2: Convex Hull
#3: Difference
#4: Dissolve
#5: Intersection
#6: Union
#7: Symetrical Difference
#8: Clip
def geoprocessing( self, myLayerA, myLayerB, myParam, myMerge, mySelectionA, mySelectionB, mySegments ):
check = QFile( self.shapefileName )
if check.exists():
if not QgsVectorFileWriter.deleteShapeFile( self.shapefileName ):
QMessageBox.warning( self, self.tr("Geoprocessing"), self.tr( "Unable to delete existing shapefile." ) )
return
self.buttonOk.setEnabled( False )
self.testThread = geoprocessingThread( self.iface.mainWindow(), self, self.myFunction, myLayerA,
myLayerB, myParam, myMerge, mySelectionA, mySelectionB, mySegments, self.shapefileName, self.encoding )
QObject.connect( self.testThread, SIGNAL( "runFinished(PyQt_PyObject)" ), self.runFinishedFromThread )
QObject.connect( self.testThread, SIGNAL( "runStatus(PyQt_PyObject)" ), self.runStatusFromThread )
QObject.connect( self.testThread, SIGNAL( "runRange(PyQt_PyObject)" ), self.runRangeFromThread )
self.cancel_close.setText( self.tr("Cancel") )
QObject.connect( self.cancel_close, SIGNAL( "clicked()" ), self.cancelThread )
self.testThread.start()
return True
def cancelThread( self ):
self.testThread.stop()
self.buttonOk.setEnabled( True )
def runFinishedFromThread( self, results ):
self.testThread.stop()
self.buttonOk.setEnabled( True )
self.cancel_close.setText( self.tr("Close") )
QObject.disconnect( self.cancel_close, SIGNAL( "clicked()" ), self.cancelThread )
out_text = ""
if results[3] is not None:
QMessageBox.warning( self, self.tr( "Geoprocessing" ),
self.tr( "No output created. File creation error:\n%s" ) % ( results[3] ) )
return
if (not results[2] is None and not results[2]) or not results[1] or not results [0]:
out_text = self.tr( "\nWarnings:" )
end_text = self.tr( "\nSome output geometries may be missing or invalid.\n\nWould you like to add the new layer anyway?" )
else:
out_text = "\n"
end_text = self.tr( "\n\nWould you like to add the new layer to the TOC?" )
if not results[2] is None:
if not results[2]:
out_text = out_text + self.tr( "\nInput CRS error: Different input coordinate reference systems detected, results may not be as expected.")
else:
out_text = out_text + self.tr( "\nInput CRS error: One or more input layers missing coordinate reference information, results may not be as expected.")
if not results[1]:
out_text = out_text + self.tr( "\nFeature geometry error: One or more output features ignored due to invalid geometry.")
if not results[0]:
out_text = out_text + self.tr( "\nGEOS geoprocessing error: One or more input features have invalid geometry.")
addToTOC = QMessageBox.question( self, self.tr("Geoprocessing"), self.tr( "Created output shapefile:\n%s\n%s%s" ) % ( unicode( self.shapefileName ), out_text, end_text ), QMessageBox.Yes, QMessageBox.No, QMessageBox.NoButton )
if addToTOC == QMessageBox.Yes:
if not ftools_utils.addShapeToCanvas( unicode( self.shapefileName ) ):
QMessageBox.warning( self, self.tr("Geoprocessing"), self.tr( "Error loading output shapefile:\n%s" ) % ( unicode( self.shapefileName ) ))
self.populateLayers()
def runStatusFromThread( self, status ):
self.progressBar.setValue( status )
def runRangeFromThread( self, range_vals ):
self.progressBar.setRange( range_vals[ 0 ], range_vals[ 1 ] )
class geoprocessingThread( QThread ):
def __init__( self, parentThread, parentObject, function, myLayerA, myLayerB,
myParam, myMerge, mySelectionA, mySelectionB, mySegments, myName, myEncoding ):
QThread.__init__( self, parentThread )
self.parent = parentObject
self.running = False
self.myFunction = function
self.myLayerA = myLayerA
self.myLayerB = myLayerB
self.myParam = myParam
self.myMerge = myMerge
self.mySelectionA = mySelectionA
self.mySelectionB = mySelectionB
self.mySegments = int( mySegments )
self.myName = myName
self.myEncoding = myEncoding
def run( self ):
self.running = True
self.vlayerA = ftools_utils.getVectorLayerByName( self.myLayerA )
error = None
if self.myFunction == 1 or self.myFunction == 2 or self.myFunction == 4:
( self.myParam, useField ) = self.checkParameter( self.vlayerA, self.myParam )
if not self.myParam is None:
if self.myFunction == 1:
geos, feature, match, error = self.buffering( useField )
elif self.myFunction == 2:
geos, feature, match, error = self.convex_hull( useField )
elif self.myFunction == 4:
geos, feature, match, error = self.dissolve( useField )
else:
self.vlayerB = ftools_utils.getVectorLayerByName( self.myLayerB )
if self.myFunction == 3:
geos, feature, match, error = self.difference()
elif self.myFunction == 5:
geos, feature, match, error = self.intersect()
elif self.myFunction == 6:
geos, feature, match, error = self.union()
elif self.myFunction == 7:
geos, feature, match, error = self.symetrical_difference()
elif self.myFunction == 8:
geos, feature, match, error = self.clip()
self.emit( SIGNAL( "runFinished(PyQt_PyObject)" ), (geos, feature, match, error) )
self.emit( SIGNAL( "runStatus(PyQt_PyObject)" ), 0 )
def stop(self):
self.running = False
def buffering( self, useField ):
GEOS_EXCEPT = True
FEATURE_EXCEPT = True
vproviderA = self.vlayerA.dataProvider()
writer = QgsVectorFileWriter( self.myName, self.myEncoding, vproviderA.fields(),
QGis.WKBPolygon, vproviderA.crs() )
# check if writer was created properly, if not, return with error
if writer.hasError():
return GEOS_EXCEPT, FEATURE_EXCEPT, True, writer.errorMessage()
outFeat = QgsFeature()
inFeat = QgsFeature()
inGeom = QgsGeometry()
outGeom = QgsGeometry()
nElement = 0
# there is selection in input layer
if self.mySelectionA:
nFeat = self.vlayerA.selectedFeatureCount()
selectionA = self.vlayerA.selectedFeatures()
self.emit( SIGNAL( "runStatus(PyQt_PyObject)" ), 0 )
self.emit( SIGNAL( "runRange(PyQt_PyObject)" ), ( 0, nFeat ) )
# with dissolve
if self.myMerge:
first = True
for inFeat in selectionA:
atMap = inFeat.attributes()
if useField:
value = atMap[ self.myParam ].doDouble()[ 0 ]
else:
value = self.myParam
inGeom = QgsGeometry( inFeat.geometry() )
try:
outGeom = inGeom.buffer( float( value ), self.mySegments )
if first:
tempGeom = QgsGeometry( outGeom )
first = False
else:
try:
tempGeom = tempGeom.combine( outGeom )
except:
GEOS_EXCEPT = False
continue
except:
GEOS_EXCEPT = False
continue
nElement += 1
self.emit( SIGNAL( "runStatus(PyQt_PyObject)" ), nElement )
try:
outFeat.setGeometry( tempGeom )
writer.addFeature( outFeat )
except:
FEATURE_EXCEPT = False
# without dissolve
else:
for inFeat in selectionA:
atMap = inFeat.attributes()
if useField:
value = atMap[ self.myParam ]
else:
value = self.myParam
inGeom = QgsGeometry( inFeat.geometry() )
try:
outGeom = inGeom.buffer( float( value ), self.mySegments )
try:
outFeat.setGeometry( outGeom )
outFeat.setAttributes( atMap )
writer.addFeature( outFeat )
except:
FEATURE_EXCEPT = False
continue
except:
GEOS_EXCEPT = False
continue
nElement += 1
self.emit( SIGNAL( "runStatus(PyQt_PyObject)" ), nElement )
# there is no selection in input layer
else:
nFeat = vproviderA.featureCount()
self.emit( SIGNAL( "runStatus(PyQt_PyObject)" ), 0 )
self.emit( SIGNAL( "runRange(PyQt_PyObject)" ), ( 0, nFeat ) )
# with dissolve
if self.myMerge:
first = True
fit = vproviderA.getFeatures()
while fit.nextFeature( inFeat ):
atMap = inFeat.attributes()
if useField:
value = atMap[ self.myParam ]
else:
value = self.myParam
inGeom = QgsGeometry( inFeat.geometry() )
try:
outGeom = inGeom.buffer( float( value ), self.mySegments )
if first:
tempGeom = QgsGeometry( outGeom )
first = False
else:
try:
tempGeom = tempGeom.combine( outGeom )
except:
GEOS_EXCEPT = False
continue
except:
GEOS_EXCEPT = False
continue
nElement += 1
self.emit( SIGNAL( "runStatus(PyQt_PyObject)" ), nElement )
try:
outFeat.setGeometry( tempGeom )
writer.addFeature( outFeat )
except:
FEATURE_EXCEPT = False
# without dissolve
else:
fit = vproviderA.getFeatures()
while fit.nextFeature( inFeat ):
atMap = inFeat.attributes()
if useField:
value = atMap[ self.myParam ]
else:
value = self.myParam
inGeom = QgsGeometry( inFeat.geometry() )
try:
outGeom = inGeom.buffer( float( value ), self.mySegments )
try:
outFeat.setGeometry( outGeom )
outFeat.setAttributes( atMap )
writer.addFeature( outFeat )
except:
FEATURE_EXCEPT = False
continue
except:
GEOS_EXCEPT = False
continue
nElement += 1
self.emit( SIGNAL( "runStatus(PyQt_PyObject)" ), nElement )
del writer
return GEOS_EXCEPT, FEATURE_EXCEPT, True, None
def convex_hull(self, useField ):
GEOS_EXCEPT = True
FEATURE_EXCEPT = True
vproviderA = self.vlayerA.dataProvider()
# creating fields
idField = QgsField("outID", QVariant.String)
areaField = QgsField("area", QVariant.Double)
perimField = QgsField("perim", QVariant.Double)
# appending fields
outFeatFields = QgsFields()
outFeatFields.append(idField)
outFeatFields.append(areaField)
outFeatFields.append(perimField)
#
writer = QgsVectorFileWriter( self.myName, self.myEncoding, outFeatFields,
QGis.WKBPolygon, vproviderA.crs() )
if writer.hasError():
return GEOS_EXCEPT, FEATURE_EXCEPT, True, writer.errorMessage()
inFeat = QgsFeature()
outFeat = QgsFeature()
# set feature fields
outFeat.setFields(outFeatFields)
#
inGeom = QgsGeometry()
outGeom = QgsGeometry()
nElement = 0
# there is selection in input layer
if self.mySelectionA:
nFeat = self.vlayerA.selectedFeatureCount()
selectionA = self.vlayerA.selectedFeatures()
if useField:
unique = ftools_utils.getUniqueValues( vproviderA, self.myParam )
nFeat = nFeat * len( unique )
self.emit( SIGNAL( "runStatus(PyQt_PyObject)" ), 0 )
self.emit( SIGNAL( "runRange(PyQt_PyObject)" ), ( 0, nFeat ) )
for i in unique:
hull = []
first = True
outID = 0
for inFeat in selectionA:
atMap = inFeat.attributes()
idVar = atMap[ self.myParam ]
if idVar == i:
if first:
outID = idVar
first = False
inGeom = QgsGeometry( inFeat.geometry() )
points = ftools_utils.extractPoints( inGeom )
hull.extend( points )
nElement += 1
self.emit( SIGNAL( "runStatus(PyQt_PyObject)" ), nElement )
if len( hull ) >= 3:
tmpGeom = QgsGeometry( outGeom.fromMultiPoint( hull ) )
try:
outGeom = tmpGeom.convexHull()
outFeat.setGeometry( outGeom )
(area, perim) = self.simpleMeasure( outGeom )
outFeat.setAttribute( "outID", outID )
outFeat.setAttribute( "area", area )
outFeat.setAttribute( "perim", perim )
writer.addFeature( outFeat )
except:
GEOS_EXCEPT = False
continue
else:
self.emit( SIGNAL( "runStatus(PyQt_PyObject)" ), 0 )
self.emit( SIGNAL( "runRange(PyQt_PyObject)" ), ( 0, nFeat ) )
hull = []
for inFeat in selectionA:
inGeom = QgsGeometry( inFeat.geometry() )
points = ftools_utils.extractPoints( inGeom )
hull.extend( points )
nElement += 1
self.emit( SIGNAL( "runStatus(PyQt_PyObject)" ), nElement )
tmpGeom = QgsGeometry( outGeom.fromMultiPoint( hull ) )
try:
outGeom = tmpGeom.convexHull()
outFeat.setGeometry( outGeom )
writer.addFeature( outFeat )
except:
GEOS_EXCEPT = False
# there is no selection in input layer
else:
nFeat = vproviderA.featureCount()
if useField:
unique = ftools_utils.getUniqueValues( vproviderA, self.myParam )
nFeat = nFeat * len( unique )
self.emit( SIGNAL( "runStatus(PyQt_PyObject)" ), 0 )
self.emit( SIGNAL( "runRange(PyQt_PyObject)" ), ( 0, nFeat ) )
for i in unique:
hull = []
first = True
outID = 0
fitA = vproviderA.getFeatures()
while fitA.nextFeature( inFeat ):
atMap = inFeat.attributes()
idVar = atMap[ self.myParam ]
if idVar == i:
if first:
outID = idVar
first = False
inGeom = QgsGeometry( inFeat.geometry() )
points = ftools_utils.extractPoints( inGeom )
hull.extend( points )
nElement += 1
self.emit( SIGNAL( "runStatus(PyQt_PyObject)" ), nElement )
if len( hull ) >= 3:
tmpGeom = QgsGeometry( outGeom.fromMultiPoint( hull ) )
try:
outGeom = tmpGeom.convexHull()
outFeat.setGeometry( outGeom )
(area, perim) = self.simpleMeasure( outGeom )
outFeat.setAttribute( "outID", outID )
outFeat.setAttribute( "area", area )
outFeat.setAttribute( "perim", perim )
writer.addFeature( outFeat )
except:
GEOS_EXCEPT = False
continue
else:
self.emit( SIGNAL( "runStatus(PyQt_PyObject)" ), 0 )
self.emit( SIGNAL( "runRange(PyQt_PyObject)" ), ( 0, nFeat ) )
hull = []
fitA = vproviderA.getFeatures()
while fitA.nextFeature( inFeat ):
inGeom = QgsGeometry( inFeat.geometry() )
points = ftools_utils.extractPoints( inGeom )
hull.extend( points )
nElement += 1
self.emit( SIGNAL( "runStatus(PyQt_PyObject)" ), nElement )
tmpGeom = QgsGeometry( outGeom.fromMultiPoint( hull ) )
try:
outGeom = tmpGeom.convexHull()
outFeat.setGeometry( outGeom )
writer.addFeature( outFeat )
except:
GEOS_EXCEPT = False
del writer
return GEOS_EXCEPT, FEATURE_EXCEPT, True, None
def dissolve( self, useField ):
GEOS_EXCEPT = True
FEATURE_EXCEPT = True
vproviderA = self.vlayerA.dataProvider()
writer = QgsVectorFileWriter( self.myName, self.myEncoding, vproviderA.fields(),
vproviderA.geometryType(), vproviderA.crs() )
if writer.hasError():
return GEOS_EXCEPT, FEATURE_EXCEPT, True, writer.errorMessage()
inFeat = QgsFeature()
outFeat = QgsFeature()
nElement = 0
attrs = None
# there is selection in input layer
if self.mySelectionA:
nFeat = self.vlayerA.selectedFeatureCount()
selectionA = self.vlayerA.selectedFeatures()
if not useField:
self.emit( SIGNAL( "runStatus(PyQt_PyObject)" ), 0 )
self.emit( SIGNAL( "runRange(PyQt_PyObject)" ), ( 0, nFeat ) )
first = True
for inFeat in selectionA:
nElement += 1
self.emit( SIGNAL( "runStatus(PyQt_PyObject)" ), nElement )
if first:
attrs = inFeat.attributes()
tmpInGeom = QgsGeometry( inFeat.geometry() )
outFeat.setGeometry( tmpInGeom )
first = False
else:
tmpInGeom = QgsGeometry( inFeat.geometry() )
tmpOutGeom = QgsGeometry( outFeat.geometry() )
try:
tmpOutGeom = QgsGeometry( tmpOutGeom.combine( tmpInGeom ) )
outFeat.setGeometry( tmpOutGeom )
except:
GEOS_EXCEPT = False
continue
outFeat.setAttributes( attrs )
writer.addFeature( outFeat )
else:
self.emit( SIGNAL( "runStatus(PyQt_PyObject)" ), 0)
self.emit( SIGNAL( "runRange(PyQt_PyObject)" ), ( 0, nFeat ) )
outFeats = {}
attrs = {}
for inFeat in selectionA:
nElement += 1
self.emit( SIGNAL( "runStatus(PyQt_PyObject)" ), nElement )
atMap = inFeat.attributes()
tempItem = unicode(atMap[self.myParam]).strip()
if not (tempItem in outFeats):
outFeats[tempItem] = QgsGeometry(inFeat.geometry())
attrs[tempItem] = atMap
else:
try:
outFeats[tempItem] = outFeats[tempItem].combine(inFeat.geometry())
except:
GEOS_EXCEPT = False
continue
for k in outFeats.keys():
feature = QgsFeature()
feature.setAttributes(attrs[k])
feature.setGeometry(outFeats[k])
writer.addFeature( feature )
# there is no selection in input layer
else:
nFeat = vproviderA.featureCount()
if not useField:
self.emit( SIGNAL( "runStatus(PyQt_PyObject)" ), 0)
self.emit( SIGNAL( "runRange(PyQt_PyObject)" ), ( 0, nFeat ) )
first = True
fitA = vproviderA.getFeatures()
while fitA.nextFeature( inFeat ):
nElement += 1
self.emit( SIGNAL( "runStatus(PyQt_PyObject)" ), nElement )
if first:
attrs = inFeat.attributes()
tmpInGeom = QgsGeometry( inFeat.geometry() )
outFeat.setGeometry( tmpInGeom )
first = False
else:
tmpInGeom = QgsGeometry( inFeat.geometry() )
tmpOutGeom = QgsGeometry( outFeat.geometry() )
try:
tmpOutGeom = QgsGeometry( tmpOutGeom.combine( tmpInGeom ) )
outFeat.setGeometry( tmpOutGeom )
except:
GEOS_EXCEPT = False
continue
outFeat.setAttributes( attrs )
writer.addFeature( outFeat )
else:
self.emit( SIGNAL( "runStatus(PyQt_PyObject)" ), 0)
self.emit( SIGNAL( "runRange(PyQt_PyObject)" ), ( 0, nFeat ) )
outFeats = {}
attrs = {}
fitA = vproviderA.getFeatures()
while fitA.nextFeature( inFeat ):
nElement += 1
self.emit( SIGNAL( "runStatus(PyQt_PyObject)" ), nElement )
atMap = inFeat.attributes()
tempItem = unicode(atMap[self.myParam]).strip()
if not (tempItem in outFeats):
outFeats[tempItem] = QgsGeometry(inFeat.geometry())
attrs[tempItem] = atMap
else:
try:
outFeats[tempItem] = outFeats[tempItem].combine(inFeat.geometry())
except:
GEOS_EXCEPT = False
continue
for k in outFeats.keys():
feature = QgsFeature()
feature.setAttributes(attrs[k])
feature.setGeometry(outFeats[k])
writer.addFeature( feature )
del writer
return GEOS_EXCEPT, FEATURE_EXCEPT, True, None
def difference( self ):
GEOS_EXCEPT = True
FEATURE_EXCEPT = True
vproviderA = self.vlayerA.dataProvider()
vproviderB = self.vlayerB.dataProvider()
# check for crs compatibility
crsA = vproviderA.crs()
crsB = vproviderB.crs()
if not crsA.isValid() or not crsB.isValid():
crs_match = None
else:
crs_match = crsA == crsB
writer = QgsVectorFileWriter( self.myName, self.myEncoding, vproviderA.fields(),
vproviderA.geometryType(), vproviderA.crs() )
if writer.hasError():
return GEOS_EXCEPT, FEATURE_EXCEPT, crs_match, writer.errorMessage()
inFeatA = QgsFeature()
inFeatB = QgsFeature()
outFeat = QgsFeature()
nElement = 0
index = ftools_utils.createIndex( vproviderB )
# there is selection in input layer
if self.mySelectionA:
nFeat = self.vlayerA.selectedFeatureCount()
selectionA = self.vlayerA.selectedFeatures()
self.emit( SIGNAL( "runStatus(PyQt_PyObject)" ), 0)
self.emit( SIGNAL( "runRange(PyQt_PyObject)" ), ( 0, nFeat ) )
# we have selection in overlay layer
if self.mySelectionB:
selectionB = self.vlayerB.selectedFeaturesIds()
for inFeatA in selectionA:
nElement += 1
self.emit( SIGNAL( "runStatus(PyQt_PyObject)" ), nElement )
add = True
geom = QgsGeometry( inFeatA.geometry() )
diff_geom = QgsGeometry( geom )
atMap = inFeatA.attributes()
intersects = index.intersects( geom.boundingBox() )
for id in intersects:
# is intersect feature in selection
if id in selectionB:
vproviderB.getFeatures( QgsFeatureRequest().setFilterFid( int( id ) ) ).nextFeature( inFeatB )
tmpGeom = QgsGeometry( inFeatB.geometry() )
try:
if diff_geom.intersects( tmpGeom ):
diff_geom = QgsGeometry( diff_geom.difference( tmpGeom ) )
except:
GEOS_EXCEPT = False
add = False
break
if add:
try:
outFeat.setGeometry( diff_geom )
outFeat.setAttributes( atMap )
writer.addFeature( outFeat )
except:
FEATURE_EXCEPT = False
continue
# we have no selection in overlay layer
else:
for inFeatA in selectionA:
nElement += 1
self.emit( SIGNAL( "runStatus(PyQt_PyObject)" ), nElement )
add = True
geom = QgsGeometry( inFeatA.geometry() )
diff_geom = QgsGeometry( geom )
atMap = inFeatA.attributes()
intersects = index.intersects( geom.boundingBox() )
for id in intersects:
vproviderB.getFeatures( QgsFeatureRequest().setFilterFid( int( id ) ) ).nextFeature( inFeatB )
tmpGeom = QgsGeometry( inFeatB.geometry() )
try:
if diff_geom.intersects( tmpGeom ):
diff_geom = QgsGeometry( diff_geom.difference( tmpGeom ) )
except:
GEOS_EXCEPT = False
add = False
break
if add:
try:
outFeat.setGeometry( diff_geom )
outFeat.setAttributes( atMap )
writer.addFeature( outFeat )
except:
FEATURE_EXCEPT = False
continue
# there is no selection in input layer
else:
nFeat = vproviderA.featureCount()
self.emit( SIGNAL( "runStatus(PyQt_PyObject)" ), 0 )
self.emit( SIGNAL( "runRange(PyQt_PyObject)" ), ( 0, nFeat ) )
# we have selection in overlay layer
if self.mySelectionB:
selectionB = self.vlayerB.selectedFeaturesIds()
fitA = vproviderA.getFeatures()
while fitA.nextFeature( inFeatA ):
nElement += 1
add = True
self.emit( SIGNAL( "runStatus(PyQt_PyObject)" ), nElement )
geom = QgsGeometry( inFeatA.geometry() )
diff_geom = QgsGeometry( geom )
atMap = inFeatA.attributes()
intersects = index.intersects( geom.boundingBox() )
for id in intersects:
# now check if id in selection
if id in selectionB:
vproviderB.getFeatures( QgsFeatureRequest().setFilterFid( int( id ) ) ).nextFeature( inFeatB )
tmpGeom = QgsGeometry( inFeatB.geometry() )
try:
if diff_geom.intersects( tmpGeom ):
diff_geom = QgsGeometry( diff_geom.difference( tmpGeom ) )
except:
GEOS_EXCEPT = False
add = False
break
if add:
try:
outFeat.setGeometry( diff_geom )
outFeat.setAttributes( atMap )
writer.addFeature( outFeat )
except:
FEATURE_EXCEPT = False
continue
# we have no selection in overlay layer
else:
fitA = vproviderA.getFeatures()
while fitA.nextFeature( inFeatA ):
nElement += 1
add = True
self.emit( SIGNAL( "runStatus(PyQt_PyObject)" ), nElement )
geom = QgsGeometry( inFeatA.geometry() )
diff_geom = QgsGeometry( geom )
atMap = inFeatA.attributes()
intersects = index.intersects( geom.boundingBox() )
for id in intersects:
vproviderB.getFeatures( QgsFeatureRequest().setFilterFid( int( id ) ) ).nextFeature( inFeatB )
tmpGeom = QgsGeometry( inFeatB.geometry() )
try:
if diff_geom.intersects( tmpGeom ):
diff_geom = QgsGeometry( diff_geom.difference( tmpGeom ) )
except:
GEOS_EXCEPT = False
add = False
break
if add:
try:
outFeat.setGeometry( diff_geom )
outFeat.setAttributes( atMap )
writer.addFeature( outFeat )
except:
FEATURE_EXCEPT = False
continue
del writer
return GEOS_EXCEPT, FEATURE_EXCEPT, crs_match, None
def intersect( self ):
GEOS_EXCEPT = True
FEATURE_EXCEPT = True
vproviderA = self.vlayerA.dataProvider()
vproviderB = self.vlayerB.dataProvider()
# check for crs compatibility
crsA = vproviderA.crs()
crsB = vproviderB.crs()
if not crsA.isValid() or not crsB.isValid():
crs_match = None
else:
crs_match = crsA == crsB
fields = ftools_utils.combineVectorFields( self.vlayerA, self.vlayerB )
longNames = ftools_utils.checkFieldNameLength( fields )
if longNames:
message = self.tr('Following field names are longer than 10 characters:\n%s') % ( '\n'.join(longNames) )
return GEOS_EXCEPT, FEATURE_EXCEPT, crs_match, message
writer = QgsVectorFileWriter( self.myName, self.myEncoding, fields,
vproviderA.geometryType(), vproviderA.crs() )
if writer.hasError():
return GEOS_EXCEPT, FEATURE_EXCEPT, crs_match, writer.errorMessage()
inFeatA = QgsFeature()
inFeatB = QgsFeature()
outFeat = QgsFeature()
nElement = 0
index = ftools_utils.createIndex( vproviderB )
# there is selection in input layer
if self.mySelectionA:
nFeat = self.vlayerA.selectedFeatureCount()
selectionA = self.vlayerA.selectedFeatures()
self.emit( SIGNAL( "runStatus(PyQt_PyObject)" ), 0)
self.emit( SIGNAL( "runRange(PyQt_PyObject)" ), ( 0, nFeat ) )
# we have selection in overlay layer
if self.mySelectionB:
selectionB = self.vlayerB.selectedFeaturesIds()
for inFeatA in selectionA:
nElement += 1
self.emit( SIGNAL( "runStatus(PyQt_PyObject)" ), nElement )
geom = QgsGeometry( inFeatA.geometry() )
atMapA = inFeatA.attributes()
intersects = index.intersects( geom.boundingBox() )
for id in intersects:
if id in selectionB:
vproviderB.getFeatures( QgsFeatureRequest().setFilterFid( int( id ) ) ).nextFeature( inFeatB )
tmpGeom = QgsGeometry( inFeatB.geometry() )
try:
if geom.intersects( tmpGeom ):
atMapB = inFeatB.attributes()
int_geom = QgsGeometry( geom.intersection( tmpGeom ) )
if int_geom.wkbType() == 0:
int_com = geom.combine( tmpGeom )
int_sym = geom.symDifference( tmpGeom )
int_geom = QgsGeometry( int_com.difference( int_sym ) )
try:
# Geometry list: prevents writing error
# in geometries of different types
# produced by the intersection
# fix #3549
gList = ftools_utils.getGeomType( geom.wkbType() )
if int_geom.wkbType() in gList:
outFeat.setGeometry( int_geom )
atMapA.extend( atMapB )
outFeat.setAttributes( atMapA )
writer.addFeature( outFeat )
except:
FEATURE_EXCEPT = False
continue
except:
GEOS_EXCEPT = False
break
# we don't have selection in overlay layer
else:
for inFeatA in selectionA:
nElement += 1
self.emit( SIGNAL( "runStatus(PyQt_PyObject)" ), nElement )
geom = QgsGeometry( inFeatA.geometry() )
atMapA = inFeatA.attributes()
intersects = index.intersects( geom.boundingBox() )
for id in intersects:
vproviderB.getFeatures( QgsFeatureRequest().setFilterFid( int( id ) ) ).nextFeature( inFeatB )
tmpGeom = QgsGeometry( inFeatB.geometry() )
try:
if geom.intersects( tmpGeom ):
atMapB = inFeatB.attributes()
int_geom = QgsGeometry( geom.intersection( tmpGeom ) )
if int_geom.wkbType() == 0:
int_com = geom.combine( tmpGeom )
int_sym = geom.symDifference( tmpGeom )
int_geom = QgsGeometry( int_com.difference( int_sym ) )
try:
gList = ftools_utils.getGeomType( geom.wkbType() )
if int_geom.wkbType() in gList:
outFeat.setGeometry( int_geom )
atMapA.extend( atMapB )
outFeat.setAttributes( atMapA )
writer.addFeature( outFeat )
except:
EATURE_EXCEPT = False
continue
except:
GEOS_EXCEPT = False
break
# there is no selection in input layer
else: