-
Notifications
You must be signed in to change notification settings - Fork 15
/
polygon_divider.py
1288 lines (1000 loc) · 46 KB
/
polygon_divider.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 -*-
"""
/***************************************************************************
PolygonDivider
A QGIS plugin
Divides polygons into smaller 'squareish' polygons of a specified size
Generated by Plugin Builder: http://g-sherman.github.io/Qgis-Plugin-Builder/
-------------------
begin : 2020-02-24
git sha : $Format:%H$
copyright : (C) 2023 Lune Geographic
email : [email protected]
***************************************************************************/
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
* This script divides a polygon into squareish sections of a specified size
*
* ERROR WE CAN FIX BY ADJUSTING TOLERANCE / N_SUBDIVISIONS:
* - Bracket is smaller than tolerance: the shape got smaller? OR got dramatically bigger. Can we check this? This is where we just want to cut at the last location that worked and re-calculate the division stuff.
*
* TODO'S:
* - Needs some form of form validation
* - There are two deprecated functions in this code
* - Pull out repeated file writing stuff into a function
* - Where / how often should we calculate the desired area?
* - How should we be dealing with reversing direction for subdivision?
* - Need to re-think how to deal with problems in subdivision - perhaps need to calculate all subdivisions then save all at once so we can roll back?
* - Look at saving last good bounds to narrow search interval after adjusting tolerance? Maybe use bisection to minimise the adjustment in tolerance?
* - This could be run in multiple parallel tasks (all strips calculated then divided up into processes to get squareish sections from them)
* - More minor TODO's throughout the code...
*
* @author jonnyhuck
*
"""
import sys
import os.path
from uuid import uuid4
from .resources import *
from qgis.utils import iface
from qgis.PyQt.QtGui import QIcon
from qgis.PyQt.QtWidgets import QAction, QFileDialog
from .polygon_divider_dialog import PolygonDividerDialog
from qgis.PyQt.QtCore import QVariant, QSettings, QTranslator, QCoreApplication
from qgis.core import Qgis, QgsGeometry, QgsPointXY, QgsPoint, QgsField, QgsTask, QgsFeature, QgsVectorLayer, \
QgsVectorFileWriter, QgsProject, QgsMessageLog, QgsApplication, QgsWkbTypes
class BrentError(Exception):
"""
* Simple class used for exceptions from Brent's Method.
"""
def __init__(self, value):
self.value = value
def __str__(self):
return repr(self.value)
# Global label for task messages
MESSAGE_CATEGORY = 'POLYGON DIVIDER'
class PolygonDividerTask(QgsTask):
"""
* Class extending QgsTask to handle on different thread
"""
''' INHERITED CLASS FUNCTIONS '''
def __init__(self, layer, outFilePath, target_area, absorb_flag, direction, tolerance):
"""
* Initialise the thread
"""
# call constructor for QsgThread
super().__init__("Polygon Division", QgsTask.CanCancel)
# load arguments into class variables
self.layer = layer
self.outFilePath = outFilePath
self.target_area = target_area
self.absorb_flag = absorb_flag
self.direction = direction
self.tolerance = tolerance
self.exception = None
def finished(self, result):
"""
* This function is automatically called when the task has completed (successfully or not).
* It called from the main thread, so it's safe to do GUI operations and raise Python exceptions here.
* result is the return value from self.run.
"""
# success
if result:
# Notify User
QgsMessageLog.logMessage('Polygon Division completed', MESSAGE_CATEGORY, Qgis.Success)
iface.messageBar().pushMessage("Success!", 'Polygon Division completed', level=Qgis.Success, duration=3)
# finally, open the resulting file and return it
layer = iface.addVectorLayer(self.outFilePath, 'Divided Polygon', "ogr")
# alert if invalid
if not layer.isValid():
raise Exception("Output Dataset Invalid")
# failure
else:
# failed without exception (user cancel)
if self.exception is None:
QgsMessageLog.logMessage('Polygon Division exited without exception', MESSAGE_CATEGORY, Qgis.Warning)
iface.messageBar().pushMessage("Warning:", 'Polygon Division Cancelled', level=Qgis.Warning, duration=3)
# failed with exception (raise exception)
else:
QgsMessageLog.logMessage(f'Polygon Division Exception: {self.exception}', MESSAGE_CATEGORY, Qgis.Critical)
iface.messageBar().pushMessage("Error:", f'Polygon Division Failed: {str(self.exception)}', level=Qgis.Critical)
# raise self.exception
def cancel(self):
"""
* This function is called when the task is cancelled
"""
# log that the task was cancelled
QgsMessageLog.logMessage("Polygon Division was manually cancelled by the user", MESSAGE_CATEGORY, Qgis.Info)
# run the cancel method from QgsTask
super().cancel()
''' OPERATIONAL FUNCTIONS '''
def brent(self, xa, xb, xtol, ftol, max_iter, geom, fixedCoord1, fixedCoord2, targetArea, horizontal, forward):
"""
* Brent's Method, following Wikipedia's article algorithm.
*
* - xa is the lower bracket of the interval of the solution we search.
* - xb is the upper bracket of the interval of the solution we search.
* - xtol is the minimum permitted width (in map units) of the interval before we give up.
* - ftol is the required precision of the solution.
* - max_iter is the maximum allowed number of iterations.
* - geom is the geometry we are dividing.
* - fixedCoord1 is the the first coordinate in the fixed dimension.
* - fixedCoord2 is the the second coordinate in the fixed dimension.
* - targetArea is the desired area of the section to cut off geom.
* - horizontal or vertical cut - True / False respectively
* - forward (left-right or bottom top) cut or backward (right-left or top-bottom) - True / False respectively
"""
''' SETUP '''
# standard for iterative algorithms
EPS = sys.float_info.epsilon
''' BASIC ERROR CHECKING (INTERVAL VALIDITY) '''
# check that the bracket's interval is sufficiently big for this computer to work with.
if abs(xb - xa) < EPS:
# raise BrentError("Initial bracket smaller than system epsilon.")
self.exception = BrentError("Initial bracket smaller than system epsilon.")
return False
# check lower bound
fa = self.f(xa, geom, fixedCoord1, fixedCoord2, targetArea, horizontal, forward) # first function call
if abs(fa) < ftol:
# raise BrentError("Root is equal to the lower bracket")
self.exception = BrentError("Root is equal to the lower bracket")
return False
# check upper bound
fb = self.f(xb, geom, fixedCoord1, fixedCoord2, targetArea, horizontal, forward) # second function call
if abs(fb) < ftol:
# raise BrentError("Root is equal to the upper bracket")
self.exception = BrentError("Root is equal to the upper bracket")
return False
# check if the root is bracketed.
if fa * fb > 0.0: # this is checking for different signs (to be sure we are either side of 0)
# raise BrentError("Root is not bracketed.")
self.exception = BrentError("Root is not bracketed.")
return False
''' START CALCULATION '''
# if the area from a is smaller than b, switch the values
if abs(fa) < abs(fb):
xa, xb = xb, xa
fa, fb = fb, fa
# initialise c at a (therefore at the one with the biggest area to the right of it)
xc, fc = xa, fa
# init mflag
mflag = True
# do until max iterations is reached
for i in range(max_iter):
# try to calculate `xs` by using inverse quadratic interpolation...
if fa != fc and fb != fc:
xs = (xa * fb * fc / ((fa - fb) * (fa - fc)) + xb * fa * fc / ((fb - fa) * (fb - fc)) + xc * fa * fb / ((fc - fa) * (fc - fb)))
else:
# ...if you can't, use the secant rule.
xs = xb - fb * (xb - xa) / (fb - fa)
# check if the value of `xs` is acceptable, if it isn't use bisection.
if ((xs < ((3 * xa + xb) / 4) or xs > xb) or
(mflag == True and (abs(xs - xb)) >= (abs(xb - xc) / 2)) or
(mflag == False and (abs(xs - xb)) >= (abs(xc - d) / 2)) or
(mflag == True and (abs(xb - xc)) < EPS) or
(mflag == False and (abs(xc - d)) < EPS)):
# overwrite unacceptable xs value with result from bisection
xs = (xa + xb) / 2
mflag = True
else:
mflag = False
''' THE ABOVE BLOCK USED BRENT'S METHOD TO GET A SUGGESTED VALUE FOR S,
THE BELOW BLOCK CHECKS IF IT IS GOOD, AND IF NOT SEEKS A NEW VALUE '''
# get the value from f using the new xs value
fs = self.f(xs, geom, fixedCoord1, fixedCoord2, targetArea, horizontal, forward) # repeated function call
# if the value (ideally 0) is less than the specified tolerance, return
if abs(fs) < ftol:
return xs
# if the bracket has become smaller than the tolerance (but the value wasn't reached, something is wrong)
# this can indicate the 'W' condition, where decreasing the interval increases the size of the resulting area
if abs(xb - xa) < xtol:
# raise BrentError("Bracket is smaller than tolerance.")
self.exception = BrentError("Bracket is smaller than tolerance.")
return False
# d is assigned for the first time here; it won't be used above on the first iteration because mflag is set
d = xc # it is just used in Brent's checks, not in the calculation per se
# move c to b
xc, fc = xb, fb
# move one of the interval edges to the new point, such that zero remains within the interval
# if the areas from a and s (current result) are same sign, move b to s, otherwise, move a to s
if fa * fs < 0: # different signs
xb, fb = xs, fs
else: # same sign
xa, fa = xs, fs
# if the area from a is smaller than b, switch the values
if abs(fa) < abs(fb):
xa, xb = xb, xa
fa, fb = fb, fa
# this isn't as good (ran out of iterations), but seems generally fine
return xs # NB: increasing the number of iterations doesn't seem to get any closer
def splitPoly(self, polygon, splitter, horizontal, forward):
"""
* Split a Polygon with a LineString
* Returns exactly two polygons notionally referred to as being 'left' and 'right' of the cutline.
* The relationship between them is that the 'right' polygon (the chip) is notionally cut from the 'left' one (the potato).
"""
# need to take a deep copy for the incoming polygon, as splitGeometry edits it directly...
poly = QgsGeometry(polygon)
'''
TODO: SPLITGEOMETRY IS DEPRECATED, but...
TypeError: index 0 has type 'QgsPoint' but 'QgsPointXY' is expected
Traceback (most recent call last):
File "/Users/jonnyhuck/Library/Application Support/QGIS/QGIS3/profiles/default/python/plugins/Submission/polygon_divider.py", line 126, in finished
raise self.exception
File "/Users/jonnyhuck/Library/Application Support/QGIS/QGIS3/profiles/default/python/plugins/Submission/polygon_divider.py", line 611, in run
sqArea = self.getSliceArea(interval[1] - sq + buffer, poly, fixedCoords[0], fixedCoords[1], horizontal_flag, forward_flag) # cutting from top/right
File "/Users/jonnyhuck/Library/Application Support/QGIS/QGIS3/profiles/default/python/plugins/Submission/polygon_divider.py", line 429, in getSliceArea
left, right, residual = self.splitPoly(poly, splitter, horizontal, forward)
File "/Users/jonnyhuck/Library/Application Support/QGIS/QGIS3/profiles/default/python/plugins/Submission/polygon_divider.py", line 282, in splitPoly
res, polys, topolist = poly.splitGeometry(splitter, False)
TypeError: index 0 has type 'QgsPoint' but 'QgsPointXY' is expected
This is due to...
https://github.com/qgis/QGIS/issues/37821
See deprecation notes here:
https://api.qgis.org/api/deprecated.html
'''
# parse splitter into required objects
# splitter = [QgsPointXY(splitter[0][0], splitter[0][1]), QgsPointXY(splitter[1][0], splitter[1][1])]
splitter = [QgsPoint(splitter[0][0], splitter[0][1]), QgsPoint(splitter[1][0], splitter[1][1])]
# split poly (polygon) by splitter (line)
# http://gis.stackexchange.com/questions/114414/cannot-split-a-line-using-qgsgeometry-splitgeometry-in-qgis
res, polys, topolist = poly.splitGeometry(splitter, False)
# add poly (which might be a multipolygon) to the polys array
if poly.isMultipart():
## TODO: I think that this is where we might be getting an odd error on no absorb
# if the feature is a multipolygon, explode into separate polygons for individual processing
multiGeom = poly.asMultiPolygon()
for i in multiGeom:
polys.append(QgsGeometry().fromPolygonXY(i))
else:
# ...OR load the feature into a list of one (it may be extended in the course of splitting if we create noncontiguous offcuts) and loop through it
polys.append(poly)
''' SORT RIGHT, LEFT, RESIDUAL '''
# verify that it worked and that more than one polygon was returned
if res == 0 and len(polys) >1:
if forward: ### from bottom left
if horizontal: ## cut from the bottom
# left is the top one
maxy = float('-inf')
for i in range(len(polys)):
p = polys[i].boundingBox().yMaximum()
if p > maxy:
maxy = p
maxyi = i
left = polys.pop(maxyi)
# right is the bottom one
miny = float('inf')
for i in range(len(polys)):
p = polys[i].boundingBox().yMinimum()
if p < miny:
miny = p
minyi = i
elif p == miny: # if there is a tie for which is the rightest, get the rightest in the other dimension
if polys[i].boundingBox().xMinimum() < polys[minyi].boundingBox().xMinimum(): # left
minyi = i
right = polys.pop(minyi)
else: ## cutting from the left
# left is the rightest one
maxx = float('-inf')
for i in range(len(polys)):
p = polys[i].boundingBox().xMaximum()
if p > maxx:
maxx = p
maxxi = i
left = polys.pop(maxxi)
# right is the leftest one
minx = float('inf')
for i in range(len(polys)):
p = polys[i].boundingBox().xMinimum()
if p < minx:
minx = p
minxi = i
elif p == minx: # if there is a tie for which is the rightest, get the rightest in the other dimension
if polys[i].boundingBox().yMinimum() < polys[minxi].boundingBox().yMinimum(): # bottom
minxi = i
right = polys.pop(minxi)
else: ### cut from top / right (forward_flag is false)
if horizontal: ## cut from the top
# left is the bottom one
miny = float('inf')
for i in range(len(polys)):
p = polys[i].boundingBox().yMinimum()
if p < miny:
miny = p
minyi = i
left = polys.pop(minyi)
# right is the top one
maxy = float('-inf')
for i in range(len(polys)):
p = polys[i].boundingBox().yMaximum()
if p > maxy:
maxy = p
maxyi = i
elif p == maxy: # if there is a tie for which is the rightest, get the rightest in the other dimension
if polys[i].boundingBox().xMaximum() > polys[maxyi].boundingBox().xMaximum():
maxyi = i
right = polys.pop(maxyi)
else: ## cutting from the right
# left is the leftest one
minx = float('inf')
for i in range(len(polys)):
p = polys[i].boundingBox().xMinimum()
if p < minx:
minx = p
minxi = i
left = polys.pop(minxi)
# right is the rightest one
maxx = float('-inf')
for i in range(len(polys)):
p = polys[i].boundingBox().xMaximum()
if p > maxx:
maxx = p
maxxi = i
elif p == maxx: # if there is a tie for which is the rightest, get the rightest in the other dimension
if polys[i].boundingBox().yMaximum() > polys[maxxi].boundingBox().yMaximum():
maxxi = i
right = polys.pop(maxxi)
# work out if any remaining polygons are contiguous with left or not
contiguous = []
noncontiguous = []
if len(polys) > 0:
for j in polys:
if left.touches(j):
contiguous.append(j)
else:
noncontiguous.append(j)
# join all contiguous parts back to left
if len(contiguous) > 0:
contiguous += [left]
left = QgsGeometry.unaryUnion(contiguous)
# return the two sections (left is the potato, right is the chip...), plus any noncontiguous polygons
return left, right, noncontiguous
else:
# log error
QgsMessageLog.logMessage("FAIL: Polygon division failed.", level=Qgis.Critical)
def getSliceArea(self,sliceCoord, poly, fixedCoord1, fixedCoord2, horizontal, forward):
"""
* Splits a polygon to a defined distance from the minimum value for the selected dimension and
* returns the area of the resultng polygon
"""
# construct a list of points representing a line by which to split the polygon
if horizontal:
splitter = [(fixedCoord1, sliceCoord), (fixedCoord2, sliceCoord)] # horizontal split
else:
splitter = [(sliceCoord, fixedCoord1), (sliceCoord, fixedCoord2)] # vertical split
# split the polygon
left, right, residual = self.splitPoly(poly, splitter, horizontal, forward)
# return the area of the bit you cut off
return right.area()
def f(self,sliceCoord, poly, fixedCoord1, fixedCoord2, targetArea, horizontal, forward):
"""
* Split a Polygon with a LineString, returning the area of the polygon to the right of the split
* returns the area of the polygon on the right of the splitter line
"""
# return the difference between the resulting polygon area (right of the line) and the desired area
return self.getSliceArea(sliceCoord, poly, fixedCoord1, fixedCoord2, horizontal, forward) - targetArea
''' THE MAIN FUNCTION FOR THE TASK'''
def run(self):
"""
* Actually do the processing
"""
# This whole function is in a catch-all try statement to avoid QGIS burying exceptions.
try:
# setup for progress bar ad message
QgsMessageLog.logMessage("Started Polygon Division", MESSAGE_CATEGORY, Qgis.Info)
# get data out of object
# TODO: reference these properly
layer = self.layer
outFilePath = self.outFilePath
target_area = self.target_area
absorb_flag = self.absorb_flag
direction = self.direction
# validation that the file is projected
if layer.crs().isGeographic():
QgsMessageLog.logMessage("Whoops! The Polygon Divider requires a projected dataset - please save a copy with a projected CRS and try again.", MESSAGE_CATEGORY, Qgis.Critical)
self.exception = Exception("Whoops! The Polygon Divider requires a projected dataset - please save a copy with a projected CRS and try again.")
return False
# used to control progress bar (only send signal for an increase)
currProgress = 0
self.setProgress(currProgress)
# initial settings
t = self.tolerance # initial tolerance for function rooting - this is flexible now it has been divorced from the buffer
buffer = 1e-6 # this is the buffer to ensure that an intersection occurs
# set the direction (horizontal or vertical)
if direction < 2:
horizontal_flag = True
else:
horizontal_flag = False
# True = cut from bottom / left, False = cut from top / right
if (direction == 0 or direction == 2):
forward_flag = True
else:
forward_flag = False
# this is used to make sure we don't hit an insurmountable error and just repeatedly change direction
# effectively, there are 4 directions in which we can cut, if all fail then all of these will be true and we give up
ERROR_FLAG_0 = False # tracks if increasing number of subdivisions failed
ERROR_FLAG_1 = False # tracks decreasing number of subdivisions to try and work around an error
ERROR_FLAG_2 = False # tracks change direction from forward to backward (or vice versa) by switching forward_flag
ERROR_FLAG_3 = False # tracks change cutline from horizontal to backward (or vice versa) by switching horizontal_flag
# get fields from the input shapefile
fieldList = self.layer.fields()
# TODO: NEED TO CHECK IF THEY ALREADY EXIST
# add new fields for this tool
fieldList.append(QgsField('POLY_ID', QVariant.Int))
fieldList.append(QgsField('UNIQUE_ID', QVariant.String))
fieldList.append(QgsField('AREA', QVariant.Double))
fieldList.append(QgsField('POINTX', QVariant.Int))
fieldList.append(QgsField('POINTY', QVariant.Int))
# create a new shapefile to write the results to
transform_context = QgsProject.instance().transformContext()
save_options = QgsVectorFileWriter.SaveVectorOptions()
save_options.driverName = "ESRI Shapefile"
save_options.fileEncoding = "UTF-8"
writer = QgsVectorFileWriter.create(outFilePath, fieldList, QgsWkbTypes.Polygon, layer.crs(), transform_context, save_options)
if writer.hasError() != QgsVectorFileWriter.NoError:
QgsMessageLog.logMessage(f"Error when creating shapefile: {writer.errorMessage()}", MESSAGE_CATEGORY, Qgis.Critical)
# define this to ensure that it's global
subfeatures = []
# init feature counter (for ID's)
j = 0
# how many sections will we have (for progress bar)
iter = layer.getFeatures()
totalArea = 0
for feat in iter:
totalArea += feat.geometry().area()
totalDivisions = totalArea // target_area
# check if you've been killed
if self.isCanceled():
# raise UserAbortedNotification('USER Killed')
return False
# loop through all of the features in the input data
iter = layer.getFeatures()
for feat in iter:
# verify that it is a polygon
if feat.geometry().wkbType() in [QgsWkbTypes.Polygon, QgsWkbTypes.PolygonZ,
QgsWkbTypes.PolygonM, QgsWkbTypes.PolygonZM, QgsWkbTypes.MultiPolygon,
QgsWkbTypes.MultiPolygonZ, QgsWkbTypes.MultiPolygonM, QgsWkbTypes.MultiPolygonZM]:
# get the attributes to write out
currAttributes = feat.attributes()
# extract the geometry and sort out self intersections etc. with a buffer of 0m
bufferedPolygon = feat.geometry().buffer(0, 15)
# if the buffer came back as None, skip
if bufferedPolygon is None:
QgsMessageLog.logMessage("A polygon could not be buffered by QGIS, ignoring", MESSAGE_CATEGORY, Qgis.Info)
continue
# make multipolygon into list of polygons...
subfeatures = []
if bufferedPolygon.isMultipart():
multiGeom = QgsGeometry()
multiGeom = bufferedPolygon.asMultiPolygon()
for i in multiGeom:
subfeatures.append(QgsGeometry().fromPolygonXY(i))
else:
# ...OR load the feature into a list of one (it may be extended in the course of splitting if we create noncontiguous offcuts) and loop through it
subfeatures.append(bufferedPolygon)
#loop through the geometries
for poly in subfeatures:
# how many polygons are we going to have to chop off?
nPolygons = int(poly.area() // target_area)
# (needs to be at least 1...)
if nPolygons == 0:
nPolygons = 1
# adjust the targetArea to reflect absorption if required
if absorb_flag:
targetArea = target_area + ((poly.area() % target_area) / nPolygons)
else:
targetArea = target_area
# work out the size of a square with area = targetArea if required
sq = targetArea**0.5
# until there is no more dividing to do...
while poly.area() > targetArea + t:
# the bounds are used for the interval
boundsR = poly.boundingBox()
bounds = [boundsR.xMinimum(), boundsR.yMinimum(), boundsR.xMaximum(), boundsR.yMaximum()]
# get interval and fixed coordinates (buffer otherwise there won't be an intersection between polygon and cutline!)
if horizontal_flag:
interval = bounds[1] + buffer, bounds[3] - buffer
fixedCoords = bounds[0], bounds[2]
else:
interval = bounds[0] + buffer, bounds[2] - buffer
fixedCoords = bounds[1], bounds[3]
# is the interval larger than the required square? (We know the required area is > target+t because of the while statement)
if (interval[1]-interval[0]) > sq:
# this is the resulting area of a slice the width of sq from the polygon
if forward_flag:
sqArea = self.getSliceArea(interval[0] + sq - buffer, poly, fixedCoords[0], fixedCoords[1], horizontal_flag, forward_flag) # cutting from bottom/left
else:
sqArea = self.getSliceArea(interval[1] - sq + buffer, poly, fixedCoords[0], fixedCoords[1], horizontal_flag, forward_flag) # cutting from top/right
# what is the nearest number of subdivisions of targetArea that could be extracted from that slice?
nSubdivisions = int(round(sqArea / targetArea))
# if the answer is 0, make it 1...
if nSubdivisions == 0:
nSubdivisions = 1
# make a backup copy to reset if we move from ERROR_FLAG_0 to ERROR_FLAG_1
nSubdivisions2 = nSubdivisions
'''now use Brent's method to find the optimal coordinate in the variable dimension (e.g. the y coord for a horizontal cut)'''
# if it fails, try increasing nSubdivisions (k) until it works or you get a different error
while True:
# how big must the target area be to support this many subdivisions?
initialTargetArea = nSubdivisions * targetArea
# try to split using this new value
# try to zero the equation
result = self.brent(interval[0], interval[1], 1e-6, t, 500, poly, fixedCoords[0], fixedCoords[1], initialTargetArea, horizontal_flag, forward_flag)
# if it worked (no exception raised) then exit this while loop and carry on
if result:
break
# otherwise, there must be an exception
else:
# is it a W condition error?
if self.exception.value == "Bracket is smaller than tolerance.":
# ...increase number of subdivisions and go around again
nSubdivisions += 1
continue
# not a W condition error
else:
# set flag and stop trying to adjust nSubdivisions
ERROR_FLAG_0 = True
break
# if that didn't work, try decreasing instead of increasing
if ERROR_FLAG_0:
# log message
QgsMessageLog.logMessage("Increasing number of subdivisions didn't work, try decreasing... (Division)", MESSAGE_CATEGORY, Qgis.Warning)
nSubdivisions = nSubdivisions2 # reset
limit = 1
while nSubdivisions >= limit:
# set the flag if it's the last time around
if nSubdivisions == limit:
ERROR_FLAG_1 = True
# how big must the target area be to support this many subdivisions?
initialTargetArea = nSubdivisions * targetArea
# try to split using this new value
# try to zero the equation
result = self.brent(interval[0], interval[1], 1e-6, t, 500, poly, fixedCoords[0], fixedCoords[1], initialTargetArea, horizontal_flag, forward_flag)
# if it worked (no exception raised) then exit this while loop and carry on
if result:
break
# otherwise, there must be an exception
else:
# ...increase number of subdivisions and go around again
nSubdivisions -= 1
continue
# if increasing the subdivision size didn't help, then start trying shifting directions
if ERROR_FLAG_1:
# these need resetting here otherwise it won't try to cut again, just skip to the next error!
ERROR_FLAG_0 = False
ERROR_FLAG_1 = False
# log message
QgsMessageLog.logMessage("Decreasing number of subdivisions didn't work, try playing with direction... (Division)", MESSAGE_CATEGORY, Qgis.Warning)
# switch the movement direction
if ERROR_FLAG_2 == False:
# log that this has been tried
ERROR_FLAG_2 = True
QgsMessageLog.logMessage("Reversing movement direction (Division)", MESSAGE_CATEGORY, Qgis.Warning)
# reverse the direction of movement and try again
forward_flag = not forward_flag
continue
# if the above didn't work, switch the direction of the cutline
elif ERROR_FLAG_3 == False:
# un-log 2, meaning that it will run again and so try the 4th direction
ERROR_FLAG_2 = False
# log that this has been tried
ERROR_FLAG_3 = True
QgsMessageLog.logMessage("Reversing cutline direction (Division)", MESSAGE_CATEGORY, Qgis.Warning)
# reverse the cutline direction and try again
horizontal_flag = not horizontal_flag
continue
# if none of the above worked, just skip it and move to a new feature
else:
''' WRITE THE UNSPLITTABLE POLYGON TO THE SHAPEFILE ANYWAY '''
# make a feature with the right schema
fet = QgsFeature()
fet.setFields(fieldList)
# populate inherited attributes
for a in range(len(currAttributes)):
fet[a] = currAttributes[a]
# populate new attributes
fet.setAttribute('POLY_ID', j)
fet.setAttribute('UNIQUE_ID', str(uuid4()))
fet.setAttribute('AREA', poly.area())
# add the geometry to the feature
fet.setGeometry(poly)
# write the feature to the out file
writer.addFeature(fet)
# increment feature counter and
j+=1
# update progress bar if required
if j // totalDivisions * 100 > currProgress:
self.setProgress(j // totalDivisions * 100)
# log that there was a problem
QgsMessageLog.logMessage("There was an un-dividable polygon in this dataset.", MESSAGE_CATEGORY, Qgis.Warning)
# on to the next one, hopefully with more luck!
continue
# if it worked, reset the flags
ERROR_FLAG_0 = False
ERROR_FLAG_1 = False
ERROR_FLAG_2 = False
ERROR_FLAG_3 = False
# create the desired cutline as lists of QgsPoints
if horizontal_flag:
line = [(fixedCoords[0], result), (fixedCoords[1], result)] # horizontal split
else:
line = [(result, fixedCoords[0]), (result, fixedCoords[1])] # vertical split
# calculate the resulting polygons - poly will be sliced again, initialSlice will be subdivided
poly, initialSlice, residuals = self.splitPoly(poly, line, horizontal_flag, forward_flag)
# put the residuals in the list to be processed
subfeatures += residuals
# bounds not bigger than sq, so no division necessary, just subdivide this last one directly (nothing will happen if it can't be subdivided)
else:
# set the remainder of the polygon as the final slice, and poly to an empty polygon
initialSlice = poly
poly = QgsGeometry.fromPolygonXY([[]])
# what is the nearest number of subdivisions of targetArea that could be extracted from that slice? (must be at least 1)
# TODO: verify this doesn't need rounding
nSubdivisions = int(initialSlice.area() // targetArea) # shouldn't need rounding...
if nSubdivisions == 0:
nSubdivisions = 1
#...then divide that into sections of targetArea
for k in range(nSubdivisions-1): # nCuts = nPieces - 1
# the bounds are used for the interval
sliceBoundsR = initialSlice.boundingBox()
sliceBounds = [sliceBoundsR.xMinimum(), sliceBoundsR.yMinimum(), sliceBoundsR.xMaximum(), sliceBoundsR.yMaximum()]
# get the slice direction (opposite to main direction)
sliceHorizontal = not horizontal_flag
if sliceHorizontal:
# get interval and fixed coordinates
sliceInterval = sliceBounds[1] + buffer, sliceBounds[3] - buffer # buffer otherwise there won't be an intersection between polygon and cutline!
sliceFixedCoords = sliceBounds[0], sliceBounds[2]
else:
# get interval and fixed coordinates
sliceInterval = sliceBounds[0] + buffer, sliceBounds[2] - buffer # buffer otherwise there won't be an intersection between polygon and cutline!
sliceFixedCoords = sliceBounds[1], sliceBounds[3]
# restore the tolerance (may be adjusted in the below loop)
tol = t
# infinite loop
while True:
# brent's method to find the optimal coordinate in the variable dimension (e.g. the y coord for a horizontal cut)
# search for result
sliceResult = self.brent(sliceInterval[0], sliceInterval[1], 1e-6, tol, 500, initialSlice, sliceFixedCoords[0], sliceFixedCoords[1], targetArea, sliceHorizontal, forward_flag)
# stop searching if result is found
if sliceResult:
break
else:
# if it is a W condition error, double the tolerance
if self.exception.value == "Bracket is smaller than tolerance.":
QgsMessageLog.logMessage(self.exception.value + ": increasing tolerance (Subdivision)", MESSAGE_CATEGORY, Qgis.Warning)
# double the tolerance and try again
tol *= 2
continue
# otherwise, give up and try something else
else:
# set the flag that this has been tried and move on
ERROR_FLAG_1 = True
break
''' IF THE ABOVE DIDNT WORK THEN WE NEED TO TRY MORE DRASTIC MEASURES '''
# try reversing the movement direction
if ERROR_FLAG_1 and not ERROR_FLAG_2: # (NB: Subdivision does not use Errorflag 0)
# log that this has been tried
ERROR_FLAG_2 = True
QgsMessageLog.logMessage("Reversing movement direction (Subdivision)", MESSAGE_CATEGORY, Qgis.Warning)
# reverse the direction of movement and try again
forward_flag = not forward_flag
continue
# if that didn't work, switch the direction of the cutline
elif ERROR_FLAG_1 and not ERROR_FLAG_3:
# log that this has been tried
ERROR_FLAG_3 = True
QgsMessageLog.logMessage("Reversing cutline direction (Subdivision):", MESSAGE_CATEGORY, Qgis.Warning)
# reverse the cutline direction and pass back to the outer division to try again in the opposite direction (otherwise we would get long thin strips, not squares)
horizontal_flag = not horizontal_flag
break # this should mean that the 'else' for this statement will never be reached
# if it worked, reset the flags
ERROR_FLAG_1 = False
ERROR_FLAG_2 = False
ERROR_FLAG_3 = False
# create the desired cutline as lists of QgsPoints
if horizontal_flag:
sliceLine = [(sliceResult, sliceFixedCoords[0]), (sliceResult, sliceFixedCoords[1])] # horizontal split
else:
sliceLine = [(sliceFixedCoords[0], sliceResult), (sliceFixedCoords[1], sliceResult)] # vertical split
# calculate the resulting polygons - initialSlice becomes left (to be chopped again)
initialSlice, right, residuals = self.splitPoly(initialSlice, sliceLine, sliceHorizontal, forward_flag)
# put the residuals in the list to be processed
subfeatures += residuals
''' WRITE TO SHAPEFILE '''
# make a feature with the right schema
fet = QgsFeature()
fet.setFields(fieldList)
# populate inherited attributes
for a in range(len(currAttributes)):
fet[a] = currAttributes[a]
# calculate representative point
pt = right.pointOnSurface().asPoint()
# populate new attributes
fet.setAttribute('POLY_ID', j)
fet.setAttribute('UNIQUE_ID', str(uuid4()))
fet.setAttribute('AREA', right.area())
fet.setAttribute('POINTX', pt[0])
fet.setAttribute('POINTY', pt[1])
# add the geometry to the feature
fet.setGeometry(right)
# write the feature to the out file
writer.addFeature(fet)
# increment feature counter and
j+=1
# update progress bar if required
if int((j*1.0) / totalDivisions * 100) > currProgress:
currProgress = int((j*1.0) / totalDivisions * 100)
self.setProgress(currProgress)
## WRITE ANY OFFCUT FROM SUBDIVISION TO SHAPEFILE
# make a feature with the right schema
fet = QgsFeature()
fet.setFields(fieldList)
# populate inherited attributes
for a in range(len(currAttributes)):
fet[a] = currAttributes[a]
# calculate representative point
pt = initialSlice.pointOnSurface().asPoint()
# populate new attributes
fet.setAttribute('POLY_ID', j)
fet.setAttribute('UNIQUE_ID', str(uuid4()))
fet.setAttribute('AREA', initialSlice.area())
fet.setAttribute('POINTX', pt[0])
fet.setAttribute('POINTY', pt[1])
# add the geometry to the feature
fet.setGeometry(initialSlice)
# write the feature to the out file
writer.addFeature(fet)
# increment feature counter and
j+=1
# update progress bar if required
if int((j*1.0) / totalDivisions * 100) > currProgress:
currProgress = int((j*1.0) / totalDivisions * 100)
self.setProgress(currProgress)
try:
## WRITE ANY OFFCUT FROM DIVISION TO SHAPEFILE
# make a feature with the right schema
fet = QgsFeature()
fet.setFields(fieldList)
# populate inherited attributes
for a in range(len(currAttributes)):
fet[a] = currAttributes[a]
# calculate representative point
pt = poly.pointOnSurface().asPoint()
# populate new attributes
fet.setAttribute('POLY_ID', j)
fet.setAttribute('UNIQUE_ID', str(uuid4()))
fet.setAttribute('AREA', poly.area())
fet.setAttribute('POINTX', pt[0])
fet.setAttribute('POINTY', pt[1])
# add the geometry to the feature
fet.setGeometry(poly)
# write the feature to the out file
writer.addFeature(fet)
# increment feature counter and
j+=1
# update progress bar if required
if int((j*1.0) / totalDivisions * 100) > currProgress:
currProgress = int((j*1.0) / totalDivisions * 100)