-
Notifications
You must be signed in to change notification settings - Fork 0
/
label_grid_algorithm.py
361 lines (300 loc) · 12.2 KB
/
label_grid_algorithm.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
# -*- coding: utf-8 -*-
"""
/***************************************************************************
LabelGrid
A QGIS plugin
Select points in grid cells
Generated by Plugin Builder: http://g-sherman.github.io/Qgis-Plugin-Builder/
-------------------
begin : 2020-12-07
copyright : (C) 2020 by Mathias Gröbe
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. *
* *
***************************************************************************/
"""
__author__ = 'Mathias Gröbe'
__date__ = '2020-12-07'
__copyright__ = '(C) 2020 by Mathias Gröbe'
# This will get replaced with a git SHA1 when you do a git archive
__revision__ = '$Format:%H$'
from qgis.PyQt.QtCore import (QCoreApplication, QVariant)
from qgis.PyQt.QtGui import QIcon
from qgis.core import (QgsProcessing,
QgsFeatureSink,
QgsProcessingAlgorithm,
QgsProcessingException,
QgsProcessingParameterFeatureSource,
QgsProcessingParameterVectorDestination,
QgsProcessingParameterFeatureSink,
QgsProcessingParameterField,
QgsProcessingParameterNumber,
QgsProcessingParameterEnum,
QgsWkbTypes,
QgsGeometry,
QgsFields,
QgsField,
QgsFeature,
QgsProcessingUtils, QgsMessageLog)
import os, processing
from operator import itemgetter, attrgetter
class GridPoint:
def __init__(self, pointID, gridID, pointValue, rank):
self.pointID = pointID
self.gridID = gridID
self.pointValue = pointValue
self.rank = rank
def __repr__(self):
rep = 'Point(' + str(self.pointID) + ', ' + str(self.gridID) + ', ' + str(self.pointValue) + ', ' + str(self.rank) +')\n'
return rep
def rankPoints(point_list, desc):
rank = 1
grid = 0
ranked_list = sorted(point_list, key=attrgetter('gridID', 'pointValue'), reverse = desc)
for point in ranked_list:
if point.gridID == -1:
point.rank = 0
else:
if grid == point.gridID:
point.rank = rank
rank = rank + 1
else:
grid = point.gridID
rank = 1
point.rank = rank
rank = rank + 1
return ranked_list
class LabelGridAlgorithm(QgsProcessingAlgorithm):
# Constants used to refer to parameters and outputs. They will be
# used when calling the algorithm from another algorithm, or when
# calling from the QGIS console.
OUTPUT_POINTS = 'OUTPUT_POINTS'
OUTPUT_GRID = 'OUTPUT_GRID'
INPUT = 'INPUT'
MINMAX = 'MINMAX'
VALUE_FIELD = 'VALUE_FIELD'
FIELD_FOR_GRID_ID = 'FIELD_FOR_GRID_ID'
FIELD_FOR_SELECTION = 'FIELD_FOR_SELECTION'
GRID_TYPE = 'GRID_TYPE'
GRID_SIZE = 'GRID_SIZE'
def initAlgorithm(self, config):
# Here we define the inputs and output of the algorithm
# Input point layer
self.addParameter(
QgsProcessingParameterFeatureSource(
self.INPUT,
self.tr('Input layer'),
[QgsProcessing.TypeVectorPoint]
)
)
# Field in point layer with numeric values
self.addParameter(
QgsProcessingParameterField(
self.VALUE_FIELD,
self.tr('Field with numeric values'),
None,
self.INPUT,
QgsProcessingParameterField.Numeric)
)
# Select min or max
self.addParameter(
QgsProcessingParameterEnum(
self.MINMAX,
self.tr('Use max or min values'),
options = ['Max', 'Min'],
defaultValue = 0,
optional = False)
)
# Set grid size
self.addParameter(
QgsProcessingParameterNumber(
self.GRID_SIZE,
self.tr('Size of grid cells'),
QgsProcessingParameterNumber.Integer,
10000,
False,
1,)
)
# Select grid shape
self.addParameter(
QgsProcessingParameterEnum(
self.GRID_TYPE,
self.tr('Choose shape of the used grid cells'),
options = ['Rectangle', 'Diamond', 'Hexagon'],
defaultValue = 0,
optional = False)
)
# Chose field to grid id
self.addParameter(
QgsProcessingParameterField(
self.FIELD_FOR_GRID_ID,
self.tr('Field for storing the id of the used grid cell'),
None,
self.INPUT,
QgsProcessingParameterField.Numeric)
)
# Chose field to selection
self.addParameter(
QgsProcessingParameterField(
self.FIELD_FOR_SELECTION,
self.tr('Field for storing the ranking of the points inside the cells'),
None,
self.INPUT,
QgsProcessingParameterField.Numeric)
)
# Output points
self.addParameter(
QgsProcessingParameterFeatureSink(
self.OUTPUT_POINTS,
self.tr('Label Grid Points')
)
)
# Output grid
self.addParameter(
QgsProcessingParameterFeatureSink(
self.OUTPUT_GRID,
self.tr('Label Grid')
)
)
def processAlgorithm(self, parameters, context, feedback):
# Retrieve the feature source and sink.
source = self.parameterAsSource(parameters, self.INPUT, context)
(sink, dest_id) = self.parameterAsSink(parameters, self.OUTPUT_POINTS,
context, source.fields(), source.wkbType(), source.sourceCrs())
if source is None:
raise QgsProcessingException(self.invalidSourceError(parameters, self.INPUT))
if QgsWkbTypes.isMultiType(source.wkbType()):
raise QgsProcessingException(self.tr('Input layer is a MultiPoint layer - first convert to single points before using this algorithm.'))
# Get variables
value_field = self.parameterAsString(parameters, self.VALUE_FIELD, context)
minmax_input = self.parameterAsString(parameters, self.MINMAX, context)
field_for_selection = self.parameterAsString(parameters, self.FIELD_FOR_SELECTION, context)
field_for_grid_id = self.parameterAsString(parameters, self.FIELD_FOR_GRID_ID, context)
grid_type = self.parameterAsString(parameters, self.GRID_TYPE, context)
grid_size = self.parameterAsString(parameters, self.GRID_SIZE, context)
# Translate grid type
creategrid_grid_type = 2
if grid_type == '0': creategrid_grid_type = 2 # Rectangle
if grid_type == '1': creategrid_grid_type = 3 # Diamond
if grid_type == '2': creategrid_grid_type = 4 # Hexagon
# Create grid
grid = processing.run(
"qgis:creategrid",
{'CRS': source.sourceCrs(),
'TYPE': creategrid_grid_type,
'EXTENT': source.sourceExtent().buffered(float(grid_size) * 0.66),
'HSPACING': grid_size,
'VSPACING': grid_size,
'HOVERLAY': 0,
'VOVERLAY': 0,
'OUTPUT': parameters[self.OUTPUT_GRID]
},
context=context,
feedback=feedback
)['OUTPUT']
# Compute the number of steps to display within the progress bar and
# get features from source
total = 100.0 / source.featureCount() if source.featureCount() else 0
# check which point is in which grid cell
points = source.getFeatures()
pointList = []
# point id, grid id, value
(sink2, dest_id2) = self.parameterAsSink(
parameters,
self.OUTPUT_GRID,
context,
grid.fields(),
grid.wkbType(),
grid.sourceCrs())
# Export grid
grid_cells = grid.getFeatures()
for cell in grid_cells:
sink2.addFeature(cell, QgsFeatureSink.FastInsert)
for current, point in enumerate(points):
if feedback.isCanceled():
break
grid_cells = grid.getFeatures()
check = True
for cell in grid_cells:
if cell.geometry().contains(point.geometry()):
pointList.append(GridPoint(point.id(), cell.id(), point[value_field], None))
check = False
# if point is not cotained by one grid cell set values
if check:
pointList.append(GridPoint(point.id(), -1, None, None))
# Update progress
feedback.setProgress(int(current * total))
# search for highest/lowest value
# Handle input for min/max
if minmax_input == '1':
# use min
points = sorted(rankPoints(pointList, False), key=attrgetter('pointID'))
else:
# use max
points = sorted(rankPoints(pointList, True), key=attrgetter('pointID'))
# bring values to features
features = source.getFeatures()
for current, (feature, point) in enumerate(zip(features, points)):
# Stop the algorithm if cancel button has been clicked
if feedback.isCanceled():
break
# set grid_id
if feature.id() == point.pointID:
# write grid_id to point
feature[field_for_grid_id] = point.gridID
# write rank to point
feature[field_for_selection] = point.rank
# Add a feature in the sink
sink.addFeature(feature, QgsFeatureSink.FastInsert)
# Update the progress bar
feedback.setProgress(int(current * total))
# Return the results of the algorithm.
return {self.OUTPUT_POINTS: dest_id,
self.OUTPUT_GRID: dest_id2}
# TODO find reason for meaningless error
def name(self):
"""
Returns the algorithm name
"""
return 'Label Grid'
def displayName(self):
"""
Returns the translated algorithm name
"""
return 'Label Grid'
def group(self):
"""
Returns the name of the group this algorithm belongs to. This string
should be localised.
"""
return self.tr(self.groupId())
def groupId(self):
"""
Returns the unique ID of the group this algorithm belongs to. This
string should be fixed for the algorithm, and must not be localised.
The group id should be unique within each provider. Group id should
contain lowercase alphanumeric characters only and no spaces or other
formatting characters.
"""
return ''
def icon(self):
return QIcon(self.svgIconPath())
def svgIconPath(self):
return os.path.dirname(__file__) + '/icon/label_grid_icon.png'
def shortHelpString(self):
file = os.path.dirname(__file__) + '/help/label_grid.help'
if not os.path.exists(file):
return ''
with open(file) as helpfile:
help = helpfile.read()
return help
def tr(self, string):
return QCoreApplication.translate('Processing', string)
def createInstance(self):
return LabelGridAlgorithm()