-
Notifications
You must be signed in to change notification settings - Fork 4
/
bufferbypercentage.py
299 lines (227 loc) · 11 KB
/
bufferbypercentage.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
# -*- coding: utf-8 -*-
"""
/***************************************************************************
BufferByPercentage
A QGIS plugin
Buffer polygon features so the buffered area is a specified percentage of
the original area
-------------------
begin : 2013-10-12
copyright : (C) 2020 by Juernjakob Dugge
***************************************************************************/
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
"""
from qgis.core import (
QgsProcessingProvider,
QgsApplication,
QgsProcessing,
QgsProcessingParameterNumber,
QgsProcessingParameterField,
QgsWkbTypes
)
from qgis.PyQt.QtGui import QIcon
from processing.algs.qgis.QgisAlgorithm import QgisFeatureBasedAlgorithm
import os
pluginPath = os.path.split(os.path.dirname(__file__))[0]
def find_buffer_length(geometry, target_factor, segments):
"""Find the buffer length that scales a geometry by a certain factor."""
area_unscaled = geometry.area()
buffer_initial = 0.1 * (geometry.boundingBox().width() +
geometry.boundingBox().height())
buffer_length = secant(calculateError, buffer_initial,
2 * buffer_initial, geometry, segments,
area_unscaled, target_factor)
return buffer_length
def calculateError(buffer_length, geometry, segments, area_unscaled,
target_factor):
"""Calculate the difference between the current and the target factor."""
geometry_scaled = geometry.buffer(buffer_length, segments)
area_scaled = geometry_scaled.area()
if area_scaled == 0:
raise ValueError('Buffer length leads to zero-area polygon')
return area_scaled / area_unscaled - target_factor
# Secant method for iteratively finding the root of a function
# Taken from
# http://www.physics.rutgers.edu/~masud/computing/WPark_recipes_in_python.html
def secant(func, oldx, x, *args, **kwargs):
"""Find the root of a function"""
tolerance = kwargs.pop('tolerance', 1e-6)
max_steps = kwargs.pop('max_steps', 100)
steps = 0
dx = 0
oldf, f = func(oldx, *args), func(x, *args)
if (abs(f) > abs(oldf)): # Determine the initial search direction
oldx, x = x, oldx
oldf, f = f, oldf
while (f - oldf) != 0 and steps < max_steps:
dx = f * (x - oldx) / float(f - oldf)
if abs(dx) < tolerance * (1 + abs(x)): # Converged
return x - dx
oldx, x = x, x - dx
try:
oldf, f = f, func(x, *args)
except ValueError:
# The current step caused an invalid result. Halve the step size
x = oldx # Undo current step
f = oldf
dx *= 0.5 # Halve the step size
oldx, x = x, x - dx
oldf, f = f, func(x, *args)
steps += 1
# Did not converge
return x - dx
class BufferByPercentagePlugin:
def __init__(self, iface):
self.provider = BufferByPercentageProvider()
def initGui(self):
QgsApplication.processingRegistry().addProvider(self.provider)
def unload(self):
QgsApplication.processingRegistry().removeProvider(self.provider)
class BufferByPercentageProvider(QgsProcessingProvider):
def __init__(self):
super().__init__()
def id(self, *args, **kwargs):
return 'bufferbypercentage'
def name(self, *args, **kwargs):
return 'Buffer by Percentage'
def icon(self):
return QIcon(os.path.join(pluginPath, 'BufferByPercentage', 'icon.svg'))
def svgIconPath(self):
return os.path.join(pluginPath, 'BufferByPercentage', 'icon.svg')
def loadAlgorithms(self, *args, **kwargs):
self.addAlgorithm(BufferByFixedPercentage())
self.addAlgorithm(BufferByVariablePercentage())
class BufferByFixedPercentage(QgisFeatureBasedAlgorithm):
INPUT = 'INPUT'
OUTPUT = 'OUTPUT'
PERCENTAGE = 'PERCENTAGE'
SEGMENTS = 'SEGMENTS'
def __init__(self):
super().__init__()
self.percentage = None
self.segments = None
def name(self):
return 'fixedpercentagebuffer'
def displayName(self, *args, **kwargs):
return 'Fixed percentage buffer'
def shortHelpString(self):
return 'Given an input polygon layer and a percentage value, this ' \
'algorithm creates a buffer area for each feature so that the ' \
'area of the buffered feature is the specified percentage of ' \
'the area of the input feature.\n' \
'For example, when specifying a percentage value of 200 %, ' \
'the buffered features would have twice the area of the input ' \
'features. For a percentage value of 50 %, the buffered ' \
'features would have half the area of the input features.\n' \
'The segments parameter controls the number of line segments ' \
'to use to approximate a quarter circle when creating rounded ' \
'offsets.'
def group(self):
return self.tr('Percentage buffer')
def icon(self):
return QIcon(os.path.join(pluginPath, 'BufferByPercentage', 'icon.svg'))
def inputLayerTypes(self):
return [QgsProcessing.TypeVectorPolygon]
def outputName(self):
return self.tr('Buffer')
def outputType(self):
return QgsProcessing.TypeVectorPolygon
def outputWkbType(self, input_wkb_type):
return QgsWkbTypes.Polygon
def initParameters(self, config=None):
self.addParameter(QgsProcessingParameterNumber(self.PERCENTAGE,
self.tr('Percentage'),
type=QgsProcessingParameterNumber.Double,
defaultValue=100.0))
self.addParameter(QgsProcessingParameterNumber(self.SEGMENTS,
self.tr('Segments'),
type=QgsProcessingParameterNumber.Integer,
minValue=1,
defaultValue=5))
def prepareAlgorithm(self, parameters, context, feedback):
self.percentage = self.parameterAsDouble(parameters, self.PERCENTAGE,
context)
self.segments = self.parameterAsInt(parameters, self.SEGMENTS, context)
return True
def processFeature(self, feature, context, feedback):
input_geometry = feature.geometry()
if input_geometry:
buffer_length = find_buffer_length(input_geometry,
self.percentage / 100.0,
self.segments)
output_geometry = input_geometry.buffer(buffer_length,
self.segments)
feature.setGeometry(output_geometry)
return [feature]
class BufferByVariablePercentage(QgisFeatureBasedAlgorithm):
INPUT = 'INPUT'
OUTPUT = 'OUTPUT'
FIELD = 'FIELD'
SEGMENTS = 'SEGMENTS'
def __init__(self):
super().__init__()
self.percentage = None
self.segments = None
def name(self):
return 'variablepercentagebuffer'
def displayName(self, *args, **kwargs):
return 'Variable percentage buffer'
def shortHelpString(self):
return 'Given an input polygon layer and a percentage field, this ' \
'algorithm creates a buffer area for each feature so that the ' \
'area of the buffered feature is a specified percentage of ' \
'the area of the input feature. The percentage value is taken' \
'from the specified percentage field of each feature.\n' \
'For example, when a feature specifies a percentage value of ' \
'200 %, the buffered feature would have twice the area of ' \
'the input feature. For a percentage value of 50 %, the buffered ' \
'feature would have half the area of the input feature.\n' \
'The segments parameter controls the number of line segments ' \
'to use to approximate a quarter circle when creating rounded ' \
'offsets.'
def group(self):
return self.tr('Percentage buffer')
def icon(self):
return QIcon(os.path.join(pluginPath, 'BufferByPercentage', 'icon.svg'))
def inputLayerTypes(self):
return [QgsProcessing.TypeVectorPolygon]
def outputName(self):
return self.tr('Buffer')
def outputType(self):
return QgsProcessing.TypeVectorPolygon
def outputWkbType(self, input_wkb_type):
return QgsWkbTypes.Polygon
def initParameters(self, config=None):
self.addParameter(QgsProcessingParameterField(self.FIELD,
self.tr(
'Percentage field'),
parentLayerParameterName=self.INPUT))
self.addParameter(QgsProcessingParameterNumber(self.SEGMENTS,
self.tr('Segments'),
type=QgsProcessingParameterNumber.Integer,
minValue=1,
defaultValue=5))
def prepareAlgorithm(self, parameters, context, feedback):
self.field = self.parameterAsString(parameters,
self.FIELD, context)
self.segments = self.parameterAsInt(parameters, self.SEGMENTS,
context)
return True
def processFeature(self, feature, context, feedback):
input_geometry = feature.geometry()
percentage = feature[self.field]
if input_geometry:
buffer_length = find_buffer_length(input_geometry,
percentage / 100.0,
self.segments)
output_geometry = input_geometry.buffer(buffer_length,
self.segments)
feature.setGeometry(output_geometry)
return [feature]