-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathbeeline_algorithm.py
More file actions
213 lines (174 loc) · 7.47 KB
/
beeline_algorithm.py
File metadata and controls
213 lines (174 loc) · 7.47 KB
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
# -*- coding: utf-8 -*-
"""
/***************************************************************************
BeelineDialog
A QGIS plugin
Connect points along great circles
-------------------
begin : 2017-09-10
copyright : (C) 2017 by Peter Gipper
email : petergipper@gmail.com
***************************************************************************/
/***************************************************************************
* *
* 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
from typing import Tuple
from qgis.PyQt.QtCore import QVariant
from qgis.PyQt.QtGui import QIcon
from qgis.core import (Qgis, QgsFeature, QgsFeatureRequest, QgsPointXY, QgsGeometry, QgsDistanceArea, QgsProcessingParameterDistance, QgsProcessingParameterFeatureSource,
QgsProcessingException, QgsFeatureSink, QgsFields, QgsField, QgsProcessing, QgsProcessingParameterDefinition,
QgsProcessingAlgorithm, QgsProcessingProvider, QgsProcessingParameterFeatureSink, QgsProcessingParameterBoolean, QgsProject)
# Support both QGIS 3.x (unscoped enums) and 4.x (scoped enums under Qgis.*)
try:
_SOURCE_TYPE_VECTOR_POINT = Qgis.ProcessingSourceType.VectorPoint
except AttributeError:
_SOURCE_TYPE_VECTOR_POINT = QgsProcessing.TypeVectorPoint
try:
_FLAG_ADVANCED = Qgis.ProcessingParameterFlag.Advanced
except AttributeError:
_FLAG_ADVANCED = QgsProcessingParameterDefinition.FlagAdvanced
class BeelineProvider(QgsProcessingProvider):
def loadAlgorithms(self):
self.addAlgorithm(BeelineAlgorithm())
def id(self):
return "beelines"
def name(self):
return "Beelines"
def icon(self):
return QIcon(self.svgIconPath())
def svgIconPath(self):
return os.path.join(os.path.dirname(__file__), "icon.svg")
def longName(self):
return self.name()
class BeelineAlgorithm(QgsProcessingAlgorithm):
INPUT = "INPUT"
SEGMENT_SIZE = "SEGMENT_SIZE"
ANTIMERIDIAN_SPLIT = "ANTIMERIDIAN_SPLIT"
OUTPUT = "OUTPUT"
def initAlgorithm(self, config=None):
self.addParameter(
QgsProcessingParameterFeatureSource(
self.INPUT,
"Input Points",
types=[_SOURCE_TYPE_VECTOR_POINT],
)
)
paramSegmentSize = QgsProcessingParameterDistance(
self.SEGMENT_SIZE,
'Segment size',
parentParameterName=self.INPUT,
minValue=0,
maxValue=1.79769e+308,
defaultValue=100000
)
paramSegmentSize.setFlags(paramSegmentSize.flags() | _FLAG_ADVANCED)
self.addParameter(paramSegmentSize)
paramAntimeridian = QgsProcessingParameterBoolean(
self.ANTIMERIDIAN_SPLIT,
'Split lines at antimeridian (±180°)',
defaultValue=True
)
paramAntimeridian.setFlags(paramAntimeridian.flags() | _FLAG_ADVANCED)
self.addParameter(paramAntimeridian)
self.addParameter(
QgsProcessingParameterFeatureSink(
self.OUTPUT,
"Beelines"
)
)
def processAlgorithm(self, parameters, context, feedback):
source = self.parameterAsSource(
parameters,
self.INPUT,
context
)
if source is None:
raise QgsProcessingException(self.invalidSourceError(parameters, self.INPUT))
segmentSize = self.parameterAsDouble(
parameters,
self.SEGMENT_SIZE,
context
)
antimeridianSplit = self.parameterAsBoolean(
parameters,
self.ANTIMERIDIAN_SPLIT,
context
)
sinkFields = QgsFields()
sinkFields.append(QgsField('source_id', QVariant.Int))
sinkFields.append(QgsField('target_id', QVariant.Int))
sinkFields.append(QgsField('distance', QVariant.Double))
(sink, dest_id) = self.parameterAsSink(
parameters,
self.OUTPUT,
context,
sinkFields,
Qgis.WkbType.MultiLineString,
source.sourceCrs()
)
if sink is None:
raise QgsProcessingException(self.invalidSinkError(parameters, self.OUTPUT))
distanceArea = QgsDistanceArea()
distanceArea.setSourceCrs(source.sourceCrs(), QgsProject.instance().transformContext())
distanceArea.setEllipsoid(source.sourceCrs().ellipsoidAcronym())
# Get list of points to process
points = []
for feature in source.getFeatures(QgsFeatureRequest().setSubsetOfAttributes([], source.fields())):
if feedback.isCanceled():
break
points.append((feature.id(), feature.geometry().asPoint()))
sinkFeatureCount = sum(range(len(points)))
# Iterate over points and create arcs
k = 1
currenFeature = 0
for point1_id, point1 in points:
for point2_id, point2 in points[k:]:
if feedback.isCanceled():
break
# Set progress
currenFeature += 1
percent = int((currenFeature/float(sinkFeatureCount)) * 100)
feedback.setProgress(percent)
# Create new feature
outFeat = QgsFeature(sinkFields)
outFeat['source_id'] = point1_id
outFeat['target_id'] = point2_id
# Create beeline and add as new feature
beelineGeometry, distance = self.createGeodesicLine(distanceArea, point1, point2, segmentSize, antimeridianSplit)
outFeat.setGeometry(beelineGeometry)
outFeat['distance'] = distance
sink.addFeature(outFeat, QgsFeatureSink.Flag.FastInsert)
k += 1
infoText = f"""
Ellipsoid: {distanceArea.ellipsoid()}
Length units: {Qgis.DistanceUnit(distanceArea.lengthUnits()).name}
"""
feedback.pushInfo(infoText)
return {self.OUTPUT: dest_id}
def createGeodesicLine(self, distArea, point1: QgsPointXY, point2: QgsPointXY, segmentSize,
breakLine: bool = True) -> Tuple[QgsGeometry, float]:
if point1.isEmpty() or point2.isEmpty():
return QgsGeometry.fromWkt("LineString EMPTY"), 0.0
distance = distArea.measureLine(point1, point2)
interval = min(segmentSize, distance) if distance > 0 else segmentSize
polyline = distArea.geodesicLine(point1, point2, interval=interval, breakLine=breakLine)
return QgsGeometry.fromMultiPolylineXY(polyline), distance
def name(self):
return "beelines"
def displayName(self):
return "Beelines"
def group(self):
return ""
def groupId(self):
return ""
def shortHelpString(self):
return """Create lines along great circles between selected points"""
def createInstance(self):
return BeelineAlgorithm()