-
Notifications
You must be signed in to change notification settings - Fork 66
/
geodesicDensify.py
356 lines (314 loc) · 15.9 KB
/
geodesicDensify.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
"""
/***************************************************************************
* *
* 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. *
* *
***************************************************************************/
"""
import os
import math
from geographiclib.geodesic import Geodesic
# import traceback
from qgis.core import (
QgsCoordinateTransform, QgsPointXY, QgsFeature, QgsGeometry,
QgsProject, QgsWkbTypes)
from qgis.core import (
QgsProcessing,
QgsProcessingAlgorithm,
QgsProcessingParameterBoolean,
QgsProcessingParameterNumber,
QgsProcessingParameterFeatureSource,
QgsProcessingParameterFeatureSink)
from qgis.PyQt.QtGui import QIcon
from qgis.PyQt.QtCore import QUrl
from .settings import settings, epsg4326, geod
from .utils import tr
class GeodesicDensifyAlgorithm(QgsProcessingAlgorithm):
"""
Algorithm to densify lines and polygons using geodesic calculations.
"""
# 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.
PrmInputLayer = 'InputLayer'
PrmOutputLayer = 'OutputLayer'
PrmDiscardVertices = 'DiscardVertices'
PrmMaxSegmentLength = 'MaxSegmentLength'
def initAlgorithm(self, config):
self.addParameter(
QgsProcessingParameterFeatureSource(
self.PrmInputLayer,
tr('Line or polygon layer'),
[QgsProcessing.TypeVectorLine, QgsProcessing.TypeVectorPolygon])
)
self.addParameter(
QgsProcessingParameterBoolean(
self.PrmDiscardVertices,
tr('Discard inner vertices (lines only)'),
False,
optional=True)
)
self.addParameter(
QgsProcessingParameterNumber(
self.PrmMaxSegmentLength,
tr('Maximum line segment length (in kilometers)'),
QgsProcessingParameterNumber.Double,
defaultValue=settings.maxSegLength,
minValue=0.001,
optional=True)
)
self.addParameter(
QgsProcessingParameterFeatureSink(
self.PrmOutputLayer,
tr('Output layer'))
)
def processAlgorithm(self, parameters, context, feedback):
source = self.parameterAsSource(parameters, self.PrmInputLayer, context)
discardVertices = self.parameterAsBool(parameters, self.PrmDiscardVertices, context)
maxseglen = self.parameterAsDouble(parameters, self.PrmMaxSegmentLength, context) * 1000 # Make it in meters
wkbtype = source.wkbType()
geomtype = QgsWkbTypes.geometryType(wkbtype)
if geomtype == QgsWkbTypes.LineGeometry:
outputType = QgsWkbTypes.LineString if (
QgsWkbTypes.isSingleType(wkbtype) or discardVertices) else QgsWkbTypes.MultiLineString
(sink, dest_id) = self.parameterAsSink(
parameters, self.PrmOutputLayer,
context, source.fields(), outputType, source.sourceCrs())
num_bad = processLine(source, sink, feedback, discardVertices, maxseglen)
else:
outputType = QgsWkbTypes.Polygon if QgsWkbTypes.isSingleType(wkbtype) else QgsWkbTypes.MultiPolygon
(sink, dest_id) = self.parameterAsSink(
parameters, self.PrmOutputLayer,
context, source.fields(), outputType, source.sourceCrs())
num_bad = processPoly(source, sink, feedback, maxseglen)
if num_bad > 0:
feedback.pushInfo(tr("{} out of {} features from input layer failed to process correctly.".format(num_bad, source.featureCount())))
return {self.PrmOutputLayer: dest_id}
def name(self):
return 'geodesicdensifier'
def icon(self):
return QIcon(os.path.dirname(__file__) + '/images/geodesicDensifier.svg')
def displayName(self):
return tr('Geodesic densifier')
def group(self):
return tr('Vector geometry')
def groupId(self):
return 'vectorgeometry'
def helpUrl(self):
file = os.path.dirname(__file__) + '/index.html'
if not os.path.exists(file):
return ''
return QUrl.fromLocalFile(file).toString(QUrl.FullyEncoded)
def shortHelpString(self):
file = os.path.dirname(__file__) + '/doc/GeodesicDensifyAlgorithm.help'
if not os.path.exists(file):
return ''
with open(file) as helpf:
help = helpf.read()
return help
def createInstance(self):
return GeodesicDensifyAlgorithm()
def processPoly(source, sink, feedback, maxseglen):
layercrs = source.sourceCrs()
if layercrs != epsg4326:
transto4326 = QgsCoordinateTransform(layercrs, epsg4326, QgsProject.instance())
transfrom4326 = QgsCoordinateTransform(epsg4326, layercrs, QgsProject.instance())
total = 100.0 / source.featureCount() if source.featureCount() else 0
iterator = source.getFeatures()
num_bad = 0
for cnt, feature in enumerate(iterator):
if feedback.isCanceled():
break
try:
if not feature.geometry().isMultipart():
poly = feature.geometry().asPolygon()
numpolygons = len(poly)
if numpolygons < 1:
continue
ptset = []
# Iterate through all points in the polygon and if the distance
# is greater than the maxseglen, then add additional points.
for points in poly:
numpoints = len(points)
if numpoints < 2:
continue
# If the input is not 4326 we need to convert it to that and then back to the output CRS
ptStart = QgsPointXY(points[0][0], points[0][1])
if layercrs != epsg4326: # Convert to 4326
ptStart = transto4326.transform(ptStart)
pts = [ptStart]
for x in range(1, numpoints):
ptEnd = QgsPointXY(points[x][0], points[x][1])
if layercrs != epsg4326: # Convert to 4326
ptEnd = transto4326.transform(ptEnd)
gline = geod.InverseLine(ptStart.y(), ptStart.x(), ptEnd.y(), ptEnd.x())
# Check to see if the distance is greater than the maximum
# segment length and if so lets add additional points.
if gline.s13 > maxseglen:
n = int(math.ceil(gline.s13 / maxseglen))
seglen = gline.s13 / n
for i in range(1, n):
s = seglen * i
g = gline.Position(s, Geodesic.LATITUDE | Geodesic.LONGITUDE | Geodesic.LONG_UNROLL)
pts.append(QgsPointXY(g['lon2'], g['lat2']))
pts.append(ptEnd)
ptStart = ptEnd
if layercrs != epsg4326: # Convert each point to the output CRS
for x, pt in enumerate(pts):
pts[x] = transfrom4326.transform(pt)
ptset.append(pts)
if len(ptset) > 0:
featureout = QgsFeature()
featureout.setGeometry(QgsGeometry.fromPolygonXY(ptset))
featureout.setAttributes(feature.attributes())
sink.addFeature(featureout)
else:
multipoly = feature.geometry().asMultiPolygon()
multiset = []
for poly in multipoly:
ptset = []
for points in poly:
numpoints = len(points)
if numpoints < 2:
continue
# If the input is not 4326 we need to convert it to that and then back to the output CRS
ptStart = QgsPointXY(points[0][0], points[0][1])
if layercrs != epsg4326: # Convert to 4326
ptStart = transto4326.transform(ptStart)
pts = [ptStart]
for x in range(1, numpoints):
ptEnd = QgsPointXY(points[x][0], points[x][1])
if layercrs != epsg4326: # Convert to 4326
ptEnd = transto4326.transform(ptEnd)
gline = geod.InverseLine(ptStart.y(), ptStart.x(), ptEnd.y(), ptEnd.x())
if gline.s13 > maxseglen:
n = int(math.ceil(gline.s13 / maxseglen))
seglen = gline.s13 / n
for i in range(1, n):
s = seglen * i
g = gline.Position(s, Geodesic.LATITUDE | Geodesic.LONGITUDE | Geodesic.LONG_UNROLL)
pts.append(QgsPointXY(g['lon2'], g['lat2']))
pts.append(ptEnd)
ptStart = ptEnd
if layercrs != epsg4326: # Convert each point to the output CRS
for x, pt in enumerate(pts):
pts[x] = transfrom4326.transform(pt)
ptset.append(pts)
multiset.append(ptset)
if len(multiset) > 0:
featureout = QgsFeature()
featureout.setGeometry(QgsGeometry.fromMultiPolygonXY(multiset))
featureout.setAttributes(feature.attributes())
sink.addFeature(featureout)
except Exception:
num_bad += 1
'''s = traceback.format_exc()
feedback.pushInfo(s)'''
feedback.setProgress(int(cnt * total))
return num_bad
def processLine(source, sink, feedback, discardVertices, maxseglen):
layercrs = source.sourceCrs()
if layercrs != epsg4326:
transto4326 = QgsCoordinateTransform(layercrs, epsg4326, QgsProject.instance())
transfrom4326 = QgsCoordinateTransform(epsg4326, layercrs, QgsProject.instance())
total = 100.0 / source.featureCount() if source.featureCount() else 0
iterator = source.getFeatures()
num_bad = 0
for cnt, feature in enumerate(iterator):
if feedback.isCanceled():
break
try:
if feature.geometry().isMultipart():
seg = feature.geometry().asMultiPolyline()
else:
seg = [feature.geometry().asPolyline()]
numseg = len(seg)
if numseg < 1 or len(seg[0]) < 2:
continue
# Create a new Line Feature
fline = QgsFeature()
# If the input is not 4326 we need to convert it to that and then back to the output CRS
if discardVertices:
ptStart = QgsPointXY(seg[0][0][0], seg[0][0][1])
if layercrs != epsg4326: # Convert to 4326
ptStart = transto4326.transform(ptStart)
pts = [ptStart]
numpoints = len(seg[numseg - 1])
ptEnd = QgsPointXY(seg[numseg - 1][numpoints - 1][0], seg[numseg - 1][numpoints - 1][1])
if layercrs != epsg4326: # Convert to 4326
ptEnd = transto4326.transform(ptEnd)
gline = geod.InverseLine(ptStart.y(), ptStart.x(), ptEnd.y(), ptEnd.x())
if gline.s13 > maxseglen:
n = int(math.ceil(gline.s13 / maxseglen))
seglen = gline.s13 / n
for i in range(1, n):
s = seglen * i
g = gline.Position(s, Geodesic.LATITUDE | Geodesic.LONGITUDE | Geodesic.LONG_UNROLL)
pts.append(QgsPointXY(g['lon2'], g['lat2']))
pts.append(ptEnd)
if layercrs != epsg4326: # Convert each point back to the output CRS
for x, pt in enumerate(pts):
pts[x] = transfrom4326.transform(pt)
fline.setGeometry(QgsGeometry.fromPolylineXY(pts))
else:
if not feature.geometry().isMultipart():
line = seg[0]
numpoints = len(line)
ptStart = QgsPointXY(line[0][0], line[0][1])
if layercrs != epsg4326: # Convert to 4326
ptStart = transto4326.transform(ptStart)
pts = [ptStart]
for x in range(1, numpoints):
ptEnd = QgsPointXY(line[x][0], line[x][1])
if layercrs != epsg4326: # Convert to 4326
ptEnd = transto4326.transform(ptEnd)
gline = geod.InverseLine(ptStart.y(), ptStart.x(), ptEnd.y(), ptEnd.x())
if gline.s13 > maxseglen:
n = int(math.ceil(gline.s13 / maxseglen))
seglen = gline.s13 / n
for i in range(1, n):
s = seglen * i
g = gline.Position(s, Geodesic.LATITUDE | Geodesic.LONGITUDE | Geodesic.LONG_UNROLL)
pts.append(QgsPointXY(g['lon2'], g['lat2']))
pts.append(ptEnd)
ptStart = ptEnd
if layercrs != epsg4326: # Convert each point back to the output CRS
for x, pt in enumerate(pts):
pts[x] = transfrom4326.transform(pt)
fline.setGeometry(QgsGeometry.fromPolylineXY(pts))
else: # MultiLineString
outseg = []
for line in seg:
numpoints = len(line)
ptStart = QgsPointXY(line[0][0], line[0][1])
if layercrs != epsg4326: # Convert to 4326
ptStart = transto4326.transform(ptStart)
pts = [ptStart]
for x in range(1, numpoints):
ptEnd = QgsPointXY(line[x][0], line[x][1])
if layercrs != epsg4326: # Convert to 4326
ptEnd = transto4326.transform(ptEnd)
gline = geod.InverseLine(ptStart.y(), ptStart.x(), ptEnd.y(), ptEnd.x())
if gline.s13 > maxseglen:
n = int(math.ceil(gline.s13 / maxseglen))
seglen = gline.s13 / n
for i in range(1, n):
s = seglen * i
g = gline.Position(s, Geodesic.LATITUDE | Geodesic.LONGITUDE | Geodesic.LONG_UNROLL)
pts.append(QgsPointXY(g['lon2'], g['lat2']))
pts.append(ptEnd)
ptStart = ptEnd
if layercrs != epsg4326: # Convert each point back to the output CRS
for x, pt in enumerate(pts):
pts[x] = transfrom4326.transform(pt)
outseg.append(pts)
fline.setGeometry(QgsGeometry.fromMultiPolylineXY(outseg))
fline.setAttributes(feature.attributes())
sink.addFeature(fline)
except Exception:
num_bad += 1
feedback.setProgress(int(cnt * total))
return num_bad