-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGenSimPlotLib.py
2168 lines (1852 loc) · 95.6 KB
/
GenSimPlotLib.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 -*-
"""
Package: GenSimPlot
File: GenSimPlotLib.py
Version: 2.1
Author: Milan Koren
Year: 2024
URL: https://github.com/milan-koren/GenSimPlot
License: EUPL v1.2 (European Union Public License), https://eupl.eu/
The implementation of various classes for creating different types of simulation plots,
such as squares, circles, rectangles, and ellipses based on different criteria.
"""
from cmath import rect
import math
import random
from qgis.core import *
from PyQt5.QtCore import QVariant
from osgeo import gdal
from GenSimPlotUtilities import GProgressDialog
from GenSimPlotUtilities import GenSimPlotUtilities
#############################################################################
# SIMULATION PLOTS
#############################################################################
class PolygonPlot:
"""
The PolygonPlot class provides foundational functionality for creating and manipulating
various types of simulation plots based on polygons.
This class includes methods to set up the centroid, bounding box, and mean coordinates of a polygon,
and supports generating different simulation plot geometries, including squares, circles, rectangles, and ellipses.
Subclasses of PolygonPlot implement specific behaviors for creating each type of simulation plot
through the following virtual methods:
- createPlot(self, polygon: QgsGeometry): Initializes the plot based on the input polygon geometry.
- createGeometry(self): Defines the geometry of the simulation plot.
- clone(self): Creates a copy of the current plot instance.
- resize(self, perc: float) Adjusts the size of the plot by a specified percentage.
Attributes:
sideRatioMax (float): The maximum allowable ratio between the long and short sides of the bounding rectangle.
ellipseNumPoints (int): The number of points used to approximate an ellipse.
originalPosition (QgsPoint): The initial position of the simulation plot.
polygonArea (float): The area of the polygon associated with the plot.
polygonPerimeter (float): The perimeter of the associated polygon.
translatedPosition (QgsPoint): The current position of the simulation plot after translation.
a (float): The length of the plot's long side.
b (float): The length of the plot's short side.
geom (QgsGeometry): The geometry of the current simulation plot.
tx (float): The translation distance in the x-direction.
ty (float): The translation distance in the y-direction.
alpha (float): The rotation angle of the plot in degrees.
"""
sideRatioMax = 4.0
ellipseNumPoints = 100
def __init__(self):
self.gname = "geometry"
self.gposition = "unknown"
self.originalPosition = QgsPoint(0.0, 0.0)
self.polygonArea = 0.0
self.polygonPerimeter = 0.0
self.translatedPosition = QgsPoint(0.0, 0.0)
self.a = 0.0
self.b = 0.0
self.geom = None
self.tx = 0.0
self.ty = 0.0
self.alpha = 0.0
def setupCentroid(self, polygon: QgsGeometry):
"""
Set the initial position of simulation plot to the centroid of the polygon.
Parameters:
polygon (QgsGeometry): The polygon for which the centroid is calculated.
"""
self.originalPosition = polygon.centroid().asPoint()
self.polygonArea = polygon.area()
self.polygonPerimeter = polygon.length()
self.translatedPosition = QgsPointXY(self.originalPosition)
def setupBBox(self, polygon: QgsGeometry):
"""
Set up the initial position of plot to centroid of the bounding box of the polygon.
Parameters:
polygon (QgsGeometry): The polygon for which the bounding box is calculated.
"""
self.originalPosition = polygon.boundingBox().center()
self.polygonArea = polygon.area()
self.polygonPerimeter = polygon.length()
self.translatedPosition = QgsPointXY(self.originalPosition)
def setupMeanXY(self, polygon: QgsGeometry):
"""
Set up the initial position of plot to the mean coordinates of the polygon.
Parameters:
polygon (QgsGeometry): The polygon for which the mean coordinates are calculated.
"""
self.originalPosition = self.meanXY(polygon)
self.polygonArea = polygon.area()
self.polygonPerimeter = polygon.length()
self.translatedPosition = QgsPointXY(self.originalPosition)
def setupSquare(self):
"""
Calculates the side length of a square simulation plot that has an area equal to the given polygon.
This function ensures the simulation plot has equal long and short sides, resulting in a square plot.
"""
self.a = math.sqrt(self.polygonArea)
self.b = self.a
def createSquare(self):
"""
Creates a square simulation plot with predefined side length.
"""
cx = self.originalPosition.x()
cy = self.originalPosition.y()
a2 = self.a / 2
self.geom = QgsGeometry.fromRect(
QgsRectangle(cx - a2, cy - a2, cx + a2, cy + a2)
)
def setupCircle(self):
"""
Calculates the radius of a circular simulation plot with an area equal to the specified polygon.
Set up the long and short sides of the simulation plot to be equal.
"""
r = math.sqrt(self.polygonArea / math.pi)
self.a = 2 * r
self.b = self.a
def createCircle(self):
"""
Creates a circular simulation plot with predefined diameter and center.
"""
c = QgsPoint(self.originalPosition.x(), self.originalPosition.y())
r = self.a / 2.0
self.geom = QgsGeometry(QgsCircle(c, r, 0.0).toPolygon())
def setupRectangle(self):
"""
Calculates the dimensions of a rectangular simulation plot with an area equal to that of the specified polygon.
Determines the length of both the longer and shorter sides to achieve the specified area.
"""
d = self.polygonPerimeter * self.polygonPerimeter - 16 * self.polygonArea
if 0 < d:
d = math.sqrt(d)
else:
d = 0
self.a = (self.polygonPerimeter + d) / 4
self.b = (self.polygonPerimeter - d) / 4
if self.sideRatioMax is not None:
if self.sideRatioMax < self.a / self.b:
self.b = math.sqrt(self.polygonArea / self.sideRatioMax)
self.a = self.polygonArea / self.b
def createRectangle(self):
"""
Creates a rectangular simulation plot with predefined dimensions.
"""
cx = self.originalPosition.x()
cy = self.originalPosition.y()
a2 = self.a / 2
b2 = self.b / 2
self.geom = QgsGeometry.fromRect(
QgsRectangle(cx - a2, cy - b2, cx + a2, cy + b2)
)
def setupEllipse(self):
"""
Calculates the major and minor axis of the ellipse simulation plot of equal area of polygon.
"""
d = self.polygonPerimeter * self.polygonPerimeter - 16 * self.polygonArea
if 0 < d:
d = math.sqrt(d)
else:
d = 0
r = (self.polygonPerimeter + d) / (self.polygonPerimeter - d)
a = math.sqrt(r * self.polygonArea / math.pi)
b = a / r
if self.sideRatioMax is not None:
if self.sideRatioMax < a / b:
a = math.sqrt(self.sideRatioMax * self.polygonArea / math.pi)
b = a / self.sideRatioMax
self.a = 2 * a
self.b = 2 * b
def createEllipse(self):
"""
Creates an elliptical simulation plot with predefined major and minor axes.
"""
cx = self.originalPosition.x()
cy = self.originalPosition.y()
semiMajor = self.a / 2
semiMinor = self.b / 2
points = []
for i in range(self.ellipseNumPoints):
angle = (2 * math.pi * i) / self.ellipseNumPoints
x = semiMajor * math.cos(angle)
y = semiMinor * math.sin(angle)
p = QgsPointXY(cx + x, cy + y)
points.append(p)
points.append(points[0])
self.geom = QgsGeometry(QgsPolygon(QgsLineString(points)))
def setupFromPlot(self, plot):
"""
Sets the parameters of the simulation plot based on an existing plot.
"""
self.originalPosition = QgsPointXY(plot.originalPosition)
self.polygonArea = plot.polygonArea
self.polygonPerimeter = plot.polygonPerimeter
self.translatedPosition = QgsPointXY(plot.translatedPosition)
self.a = plot.a
self.b = plot.b
self.geom = QgsGeometry(plot.geom)
self.tx = plot.tx
self.ty = plot.ty
self.alpha = plot.alpha
def translate(self, dx, dy):
"""
Translates the simulation plot by a given distance along the x and y axes.
Parameters:
dx (float): The distance to move the plot along the x-axix.
dy (float): The distance to move the plot along the y-axis.
Returns:
A new simulation plot with the translated geometry.
"""
nplot = self.clone()
nplot.geom.translate(dx, dy)
nplot.translatedPosition = QgsPointXY(
nplot.translatedPosition.x() + dx, nplot.translatedPosition.y() + dy
)
nplot.tx += dx
nplot.ty += dy
return nplot
def rotate(self, angle):
"""
Rotates the simulation plot by a specified angle.
Parameters:
angle (float): The angle of rotation in degrees.
Returns:
A new simulation plot with the rotated geometry.
"""
nplot = self.clone()
nplot.geom.rotate(angle, nplot.translatedPosition)
nplot.alpha += angle
return nplot
def randomTranslate(self, maxPerc):
"""
Randomly translates the simulation plot within a specified percentage of its longest side length.
The plot is shifted by a random distance along both the x and y axes, where the maximum shift is
determined as a percentage of the plot's longest side.
Parameters:
maxPerc (float): The maximum percentage of the longest side length to translate the plot.
Returns:
A new simulation plot with the translated geometry.
"""
dx = self.a * math.sin(math.radians(self.alpha)) + self.b * math.cos(
math.radians(self.alpha)
)
dy = self.a * math.cos(math.radians(self.alpha)) + self.b * math.sin(
math.radians(self.alpha)
)
tx = maxPerc * dx * (2.0 * random.random() - 1.0)
ty = maxPerc * dy * (2.0 * random.random() - 1.0)
return self.translate(tx, ty)
def randomRotate(self, maxAngle):
"""
Randomly rotates the simulation plot within a specified angle range.
Parameters:
maxAngle (float): The maximum angle, in degrees, by which the plot can be randomly rotated.
Returns:
A new simulation plot with rotated geometry.
"""
angle = maxAngle * (2.0 * random.random() - 1.0)
return self.rotate(angle)
def resizeRectangle(self, perc):
"""
Resizes the simulation plot by a given percentage.
Parameters:
perc (float): the percentage to scale the simulation plot by.
"""
a = self.a * (1 + perc)
b = self.b / (1 + perc)
if a < b:
c = b
b = a
a = c
if self.sideRatioMax is not None:
if a / b <= self.sideRatioMax:
self.a = a
self.b = b
def resize(self, perc: float):
"""
Resizes the simulation plot by a specified percentage.
Parameters:
perc (float): The percentage by which to resize the simulation plot.
Returns:
A new instance of the simulation plot with the adjusted geometry.
"""
plot = self.clone()
plot.resizeRectangle(perc)
plot.createGeometry()
plot.geom.translate(plot.tx, plot.ty)
plot.geom.rotate(plot.alpha, plot.translatedPosition)
return plot
def randomResize(self, maxResizePerc: float):
"""
Randomly resizes the simulation plot by a specified maximum percentage.
Parameters:
maxResizePerc (float): The maximum percentage variation to apply when randomly resizing the plot.
Returns:
A new instance of the simulation plot with randomly adjusted geometry.
"""
perc = maxResizePerc * (2.0 * random.random() - 1.0)
return self.resize(perc)
def meanXY(self, polygon: QgsGeometry):
"""
Calculate the mean coordinates of a polygon.
Parameters:
polygon (QgsGeometry): The polygon geometry for which the mean coordinates are calculated.
Returns:
QgsPoint: A point with the mean x and y coordinates of the polygon.
"""
x = 0.0
y = 0.0
v = polygon.vertices()
m = 0
while v.hasNext():
p = v.next()
x += p.x()
y += p.y()
m += 1
if 0 < m:
x = x / m
y = y / m
return QgsPointXY(x, y)
else:
return None
class SquareByCentroid(PolygonPlot):
"""
This class represents a square simulation plot based on the centroid of a polygon.
"""
def __init__(self):
super().__init__()
self.gname = "square"
self.gposition = "centroid"
def createPlot(self, polygon: QgsGeometry):
plot = SquareByCentroid()
plot.setupCentroid(polygon)
plot.setupSquare()
plot.createSquare()
return plot
def createGeometry(self):
plot.createSquare()
def clone(self):
plot = SquareByCentroid()
plot.setupFromPlot(self)
return plot
def resize(self, perc: float):
return self.clone()
class SquareByBBox(PolygonPlot):
"""
This class represents a square simulation plot based on the bounding box of a polygon.
"""
def __init__(self):
super().__init__()
self.gname = "square"
self.gposition = "bbox"
def createPlot(self, polygon: QgsGeometry):
plot = SquareByBBox()
plot.setupBBox(polygon)
plot.setupSquare()
plot.createSquare()
return plot
def createGeometry(self):
plot.createSquare()
def clone(self):
plot = SquareByBBox()
plot.setupFromPlot(self)
return plot
def resize(self, perc: float):
return self.clone()
class SquareByMeanXY(PolygonPlot):
"""
This class represents a square simulation plot based on the mean coordinates of a polygon.
"""
def __init__(self):
super().__init__()
self.gname = "square"
self.gposition = "meanxy"
def createPlot(self, polygon: QgsGeometry):
plot = SquareByMeanXY()
plot.setupMeanXY(polygon)
plot.setupSquare()
plot.createSquare()
return plot
def createGeometry(self):
plot.createSquare()
def clone(self):
plot = SquareByMeanXY()
plot.setupFromPlot(self)
return plot
def resize(self, perc: float):
return self.clone()
class CircleByCentroid(PolygonPlot):
"""
This class represents a circular simulation plot based on the centroid of a polygon.
"""
def __init__(self):
super().__init__()
self.gname = "circle"
self.gposition = "centroid"
def createPlot(self, polygon: QgsGeometry):
plot = CircleByCentroid()
plot.setupCentroid(polygon)
plot.setupCircle()
plot.createCircle()
return plot
def createGeometry(self):
plot.createCircle()
def clone(self):
plot = CircleByCentroid()
plot.setupFromPlot(self)
return plot
def resize(self, perc: float):
return self.clone()
def rotate(self, angle):
return self.clone()
class CircleByBBox(PolygonPlot):
"""
This class represents a circular simulation plot based on the bounding box.
"""
def __init__(self):
super().__init__()
self.gname = "circle"
self.gposition = "bbox"
def createPlot(self, polygon: QgsGeometry):
plot = CircleByBBox()
plot.setupBBox(polygon)
plot.setupCircle()
plot.createCircle()
return plot
def createGeometry(self):
plot.createCircle()
def clone(self):
plot = CircleByBBox()
plot.setupFromPlot(self)
return plot
def resize(self, perc: float):
return self.clone()
def rotate(self, angle):
return self.clone()
class CircleByMeanXY(PolygonPlot):
"""
This class represents a circular simulation plot based on the mean coordinates of a polygon.
"""
def __init__(self):
super().__init__()
self.gname = "circle"
self.gposition = "meanxy"
def createPlot(self, polygon: QgsGeometry):
plot = CircleByMeanXY()
plot.setupMeanXY(polygon)
plot.setupCircle()
plot.createCircle()
return plot
def createGeometry(self):
plot.createCircle()
def clone(self):
plot = CircleByMeanXY()
plot.setupFromPlot(self)
return plot
def resize(self, perc: float):
return self.clone()
def rotate(self, angle):
return self.clone()
class RectangleByCentroid(PolygonPlot):
"""
This class represents a rectangular simulation plot based on the centroid of a polygon.
"""
def __init__(self):
super().__init__()
self.gname = "rectangle"
self.gposition = "centroid"
def createPlot(self, polygon: QgsGeometry):
plot = RectangleByCentroid()
plot.setupCentroid(polygon)
plot.setupRectangle()
plot.createRectangle()
return plot
def createGeometry(self):
self.createRectangle()
def clone(self):
plot = RectangleByCentroid()
plot.setupFromPlot(self)
return plot
class RectangleByBBox(PolygonPlot):
"""
This class represents a rectangular simulation plot based on the bounding box.
"""
def __init__(self):
super().__init__()
self.gname = "rectangle"
self.gposition = "bbox"
def createPlot(self, polygon: QgsGeometry):
plot = RectangleByBBox()
plot.setupBBox(polygon)
plot.setupRectangle()
plot.createRectangle()
return plot
def createGeometry(self):
self.createRectangle()
def clone(self):
plot = RectangleByBBox()
plot.setupFromPlot(self)
return plot
class RectangleByMeanXY(PolygonPlot):
"""
This class represents a rectangular simulation plot based on the mean coordinates.
"""
def __init__(self):
super().__init__()
self.gname = "rectangle"
self.gposition = "meanxy"
def createPlot(self, polygon: QgsGeometry):
plot = RectangleByMeanXY()
plot.setupMeanXY(polygon)
plot.setupRectangle()
plot.createRectangle()
return plot
def createGeometry(self):
self.createRectangle()
def clone(self):
plot = RectangleByMeanXY()
plot.setupFromPlot(self)
return plot
class EllipseByCentroid(PolygonPlot):
"""
This class represents an elliptical simulation plot based on the centroid of a polygon.
"""
def __init__(self):
super().__init__()
self.gname = "ellipse"
self.gposition = "centroid"
def createPlot(self, polygon: QgsGeometry):
plot = EllipseByCentroid()
plot.setupCentroid(polygon)
plot.setupEllipse()
plot.createEllipse()
return plot
def createGeometry(self):
self.createEllipse()
def clone(self):
plot = EllipseByCentroid()
plot.setupFromPlot(self)
return plot
class EllipseByBBox(PolygonPlot):
"""
This class represents an elliptical simulation plot based on the bounding box.
"""
def __init__(self):
super().__init__()
self.gname = "ellipse"
self.gposition = "bbox"
def createPlot(self, polygon: QgsGeometry):
plot = EllipseByBBox()
plot.setupBBox(polygon)
plot.setupEllipse()
plot.createEllipse()
return plot
def createGeometry(self):
self.createEllipse()
def clone(self):
plot = EllipseByBBox()
plot.setupFromPlot(self)
return plot
class EllipseByMeanXY(PolygonPlot):
"""
This class represents an elliptical simulation plot based on the mean coordinates.
"""
def __init__(self):
super().__init__()
self.gname = "ellipse"
self.gposition = "meanxy"
def createPlot(self, polygon: QgsGeometry):
plot = EllipseByMeanXY()
plot.setupMeanXY(polygon)
plot.setupEllipse()
plot.createEllipse()
return plot
def createGeometry(self):
self.createEllipse()
def clone(self):
plot = EllipseByMeanXY()
plot.setupFromPlot(self)
return plot
#############################################################################
# PLOT GENERATOR
#############################################################################
class PlotGenerator:
"""
The PlotGenerator class facilitates the generation of simulation plots from input polygon geometries.
This class provides methods to create various simulation plot shapes, including squares, circles, rectangles,
and ellipses, with flexible positioning options based on attributes such as bounding box, centroid, and mean
coordinates of the polygon. Additionally, the class supports random transformations - translations, rotations,
and reshaping - to maximize overlap with source polygons.
Attributes:
randomIterations (int): Specifies the number of random iterations for each simulation plot generation.
percTranslate (float): Defines the maximum percentage for random translations in the x and y directions.
maxAlpha (float): Sets the maximum allowable rotation angle, in degrees, for random plot rotations.
sideRatioMax (float): Limits the maximum ratio between the long and short sides of a rectangular plot.
maxResizePerc (float): Determines the maximum percentage by which a plot's size can be altered.
"""
def __init__(self):
"""
Initializes the PlotGenerator class with default values for the simulation plot generation parameters.
"""
self.setup()
def setup(
self,
randomIterations: int = 250,
percTranslate: float = 0.05,
maxAlpha: float = 5.00,
sideRatioMax: float = 4.00,
maxResizePerc: float = 0.10,
):
"""
Configures the parameters for the simulation plot generation process.
This method allows customization of the key parameters influencing how simulation plots are generated, including
the number of random iterations, maximum translation, rotation angle, aspect ratio limits, and reshaping percentage.
Parameters:
randomIterations (int): The number of random generation attempts to apply when creating each simulation plot.
Higher values can improve accuracy but may increase computation time. Default is 250.
percTranslate (float): The maximum allowable percentage for random translation in both x and y directions
relative to plot size. Default is 0.05.
maxAlpha (float): The maximum rotation angle, in degrees, for random plot rotations to enhance positional
variation. Default is 5.0 degrees.
sideRatioMax (float): The maximum allowable ratio between the longer and shorter sides of a rectangular plot,
which constrains plot shape. Default is 4.0.
maxResizePerc (float): The maximum percentage by which the plot size can be altered for reshaping, aiding
flexibility in adapting plot geometry to source data. Default is 0.10.
"""
self.randomIterations = randomIterations
self.percTranslate = percTranslate
self.maxAlpha = maxAlpha
self.sideRatioMax = sideRatioMax
self.maxResizePerc = maxResizePerc
def createSPlotFields(self, idField: QgsField):
"""
Generates a 'QgsFields' object containing fields for simulation plot attributes.
This function creates a set of fields used to store simulation plot metadata, specifically designed for associating
plots with unique forest stand IDs. The fields include identifiers essential for organizing and identifying
simulation plots within a forest management or research dataset.
Parameters:
idField (QgsField): The field containing the unique ID for each simulation plot.
Returns:
QgsFields: A 'QgsFields' object with the defined field structure for use in simulation plot layers.
"""
outputFields = QgsFields()
outputFields.append(idField)
outputFields.append(QgsField("a", QVariant.Double, "double", 6, 2))
outputFields.append(QgsField("b", QVariant.Double, "double", 6, 2))
outputFields.append(QgsField("alpha", QVariant.Double, "double", 6, 2))
outputFields.append(QgsField("perc", QVariant.Double, "double", 6, 2))
outputFields.append(QgsField("ishp", QVariant.Double, "double", 6, 2))
return outputFields
def createSPlotShapeFile(self, outputFN: str, outputFields: QgsFields, crs):
"""
Creates a new ESRI Shapefile for storing simulation plot geometries.
This function generates a vector file specifically formatted as an ESRI Shapefile to store simulation plot geometries.
The output file is initialized with a defined structure of fields and a specified Coordinate Reference System (CRS),
making it suitable for GIS analysis and visualization.
Parameters:
outputFN (str): The file path and name for the output vector file to be created.
outputFields (QgsFields): A 'QgsFields' object defining the structure of fields to include in the output file,
typically for storing simulation plot metadata.
crs (QgsCoordinateReferenceSystem): The CRS in which to save the output file, ensuring spatial accuracy and consistency.
Returns:
QgsVectorFileWriter: A 'QgsVectorFileWriter' instance associated with the newly created Shapefile, enabling
further data insertion and manipulation.
"""
svo = QgsVectorFileWriter.SaveVectorOptions()
svo.driverName = "ESRI Shapefile"
return QgsVectorFileWriter.create(
outputFN,
outputFields,
Qgis.WkbType.Polygon,
crs,
QgsCoordinateTransformContext(),
svo,
QgsFeatureSink.SinkFlags(),
None,
None,
)
def createSPlot(self, polygon: QgsGeometry, plotFactory):
"""
Generates a simulation plot using the geometry of an input polygon.
This function creates a simulation plot by utilizing the specified 'plotFactory' object, which contains
the logic to generate plot geometries based on the input polygon. It calls the 'createPlot' method
of the provided simulation plot object, ensuring that the generated plot aligns with the spatial properties
of the input polygon geometry.
Parameters:
polygon (QgsGeometry): The input polygon geometry that defines the area and shape used for generating
the simulation plot.
plotFactory: An instance of the simulation plot class (e.g. RectangleByBBox) that contains
the 'createPlot' method, responsible for creating the plot geometry.
Returns:
QgsGeometry: The generated geometry of the simulation plot.
"""
splot = plotFactory.createPlot(polygon)
sarea = polygon.intersection(splot.geom).area()
return (splot, sarea)
def createTranslatedPlot(self, polygon: QgsGeometry, plotFactory):
"""
Generates a randomly translated simulation plot to maximize overlap with an input polygon.
This function creates a simulation plot based on the provided polygon geometry. It then iteratively translates
the plot within a specified percentage ('percTranslate') to maximize the area of overlap between the plot and
the input polygon.
Parameters:
polygon (QgsGeometry): The input polygon geometry that serves as the reference for generating
and aligning the simulation plot.
plotFactory: An instance of the simulation plot class that provides the 'createPlot' and 'randomTranslate'
methods to generate and translate the plot geometry.
Returns:
SimulationPlot: The randomly translated simulation plot with the maximum overlap area with the input polygon.
"""
splot = plotFactory.createPlot(polygon)
sarea = polygon.intersection(splot.geom).area()
for i in range(self.randomIterations):
nplot = splot.randomTranslate(self.percTranslate)
narea = polygon.intersection(nplot.geom).area()
if sarea < narea:
sarea = narea
splot = nplot
return (splot, sarea)
def createRotatedSPlot(self, polygon: QgsGeometry, plotFactory):
"""
Generates a randomly rotated simulation plot to maximize overlap with an input polygon.
This function creates an initial simulation plot based on the provided polygon geometry. It then iteratively
rotates the plot within a specified maximum angle ('maxAlpha') to maximize the area of overlap between the plot
and the input polygon.
Parameters:
polygon (QgsGeometry): The input polygon geometry that serves as the reference for generating and aligning
the simulation plot.
plotFactory: An instance of the simulation plot class that provides the 'createPlot' and 'randomRotate'
methods to generate and rotate the plot geometry.
Returns:
SimulationPlot: The randomly rotated simulation plot with the maximum overlap area with the input polygon.
"""
splot = plotFactory.createPlot(polygon)
sarea = polygon.intersection(splot.geom).area()
for i in range(self.randomIterations):
nplot = splot.randomRotate(self.maxAlpha)
narea = polygon.intersection(nplot.geom).area()
if sarea < narea:
sarea = narea
splot = nplot
return (splot, sarea)
def createResizedSPlot(self, polygon: QgsGeometry, plotFactory):
"""
Generates a resized simulation plot by applying random size adjustments to maximize overlap with an input polygon.
This function initializes a simulation plot based on the provided polygon geometry and iteratively applies random
reshaping transformations. After each reshaping, the overlap area between the resized plot and the input polygon
is calculated, with the plot configuration that yields the maximum overlap being retained as the final output.
Parameters:
polygon (QgsGeometry): The input polygon geometry used as a reference for generating and optimizing the simulation plot.
plotFactory: An instance of a simulation plot class providing the 'randomResize' method for performing resize transformation.
Returns:
SimulationPlot: The resized simulation plot with the highest achieved overlap area relative to the input polygon.
"""
splot = plotFactory.createPlot(polygon)
sarea = polygon.intersection(splot.geom).area()
for i in range(self.randomIterations):
nplot = splot.randomResize(self.maxResizePerc)
narea = polygon.intersection(nplot.geom).area()
if sarea < narea:
sarea = narea
splot = nplot
return (splot, sarea)
def createOptimizedSPlot(self, polygon: QgsGeometry, plotFactory):
"""
Generates an optimized simulation plot by applying random transformations to maximize overlap with an input polygon.
This function creates an initial simulation plot based on the given polygon geometry and iteratively applies random
reshaping, translation, and rotation transformations to the plot. Each transformation sequence is evaluated for its
overlap area with the input polygon, and the plot configuration yielding the maximum overlap area is retained.
Parameters:
polygon (QgsGeometry): The input polygon geometry used as a reference for generating and optimizing the simulation plot.
plotFactory: An instance of a simulation plot class that provides 'createPlot', 'randomResize',
'randomTranslate', and 'randomRotate' methods to perform the transformations.
Returns:
SimulationPlot: The optimized simulation plot with the highest overlap area with the input polygon.
"""
splot = plotFactory.createPlot(polygon)
sarea = polygon.intersection(splot.geom).area()
for i in range(self.randomIterations):
nplot = splot.randomResize(self.maxResizePerc)
nplot = nplot.randomTranslate(self.percTranslate)
nplot = nplot.randomRotate(self.maxAlpha)
narea = polygon.intersection(nplot.geom).area()
if sarea < narea:
sarea = narea
splot = nplot
return (splot, sarea)
def createBestSPlot(self, polygon: QgsGeometry, plotFactory):
"""
Generates the most optimal simulation plot that maximizes overlap with the input polygon.
This function iterates through various shapes (square, circle, rectangle, and ellipse) and different
positioning methods (aligned with the bounding box, centered on the centroid, or centered on the mean coordinates)
to generate a simulation plot. For each combination, it applies random spatial transformations to achieve maximum
overlap area with the input polygon. The resulting plot with the highest overlap is returned.
Parameters:
polygon (QgsGeometry): The input polygon geometry used as a reference for generating and optimizing the simulation plot.
plotFactory: An instance of a simulation plot class that provides methods such as 'createPlot',
'randomResize', 'randomTranslate', and 'randomRotate' for performing transformations.
Returns:
The optimized simulation plot that achieves the maximum overlap area with the input polygon.
"""
bplot, barea = self.createOptimizedSPlot(polygon, SquareByBBox())
splot, sarea = self.createOptimizedSPlot(polygon, SquareByCentroid())
if barea < sarea:
bplot = splot
barea = sarea
splot, sarea = self.createOptimizedSPlot(polygon, SquareByMeanXY())
if barea < sarea:
bplot = splot
barea = sarea
splot, sarea = self.createOptimizedSPlot(polygon, CircleByBBox())
if barea < sarea:
bplot = splot
barea = sarea
splot, sarea = self.createOptimizedSPlot(polygon, CircleByCentroid())
if barea < sarea:
bplot = splot
barea = sarea
splot, sarea = self.createOptimizedSPlot(polygon, CircleByMeanXY())
if barea < sarea:
bplot = splot
barea = sarea
splot, sarea = self.createOptimizedSPlot(polygon, RectangleByBBox())
if barea < sarea: