-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathwnt_network_from_lines.py
363 lines (322 loc) · 12.8 KB
/
wnt_network_from_lines.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
# -*- coding: utf-8 -*-
"""
/***************************************************************************
WaterNetworkTools
A QGIS plugin
Water Network Modelling Utilities
-------------------
begin : 2019-07-19
copyright : (C) 2019 by Andrés García Martínez
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__ = 'Andrés García Martínez'
__date__ = '2019-07-19'
__copyright__ = '(C) 2019 by Andrés García Martínez'
# 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.core import (QgsFeature,
QgsField,
QgsFields,
QgsGeometry,
QgsWkbTypes,
QgsProcessing,
QgsProcessingAlgorithm,
QgsProcessingParameterNumber,
QgsProcessingParameterDistance,
QgsProcessingParameterString,
QgsProcessingParameterFeatureSink,
QgsProcessingParameterFeatureSource,
QgsPointXY
)
from . import utils_core as tools
class NetworkFromLinesAlgorithm(QgsProcessingAlgorithm):
"""
Built a network from lines.
"""
# DEFINE CONSTANTS
INPUT = 'INPUT'
TOLERANCE = 'TOLERANCE'
NODE_MASK = 'NODE_MASK'
NODE_INI = 'NODE_INI'
NODE_INC = 'NODE_INC'
LINK_MASK = 'LINK_MASK'
LINK_INI = 'LINK_INI'
LINK_INC = 'LINK_INC'
NODE_OUTPUT = 'NODE_OUTPUT'
LINK_OUTPUT = 'LINK_OUTPUT'
def tr(self, string):
"""
Returns a translatable string with the self.tr() function.
"""
return QCoreApplication.translate('Processing', string)
def createInstance(self):
"""
Create a instance and return a new copy of algorithm.
"""
return NetworkFromLinesAlgorithm()
def name(self):
"""
Returns the unique algorithm name, used for identifying the algorithm.
"""
return 'network_from_lines'
def displayName(self):
"""
Returns the translated algorithm name.
"""
return self.tr('Network from lines')
def group(self):
"""
Returns the name of the group this algorithm belongs to.
"""
return self.tr('Build')
def groupId(self):
"""
Returns the unique ID of the group this algorithm belongs to.
"""
return 'build'
def shortHelpString(self):
"""
Returns a localised short help string for the algorithm.
"""
return self.tr('''Generate an epanet network from lines.
The generated network consists of two layers: nodes and links.
Line ends not separated more than tolerance are merged into a node.
The node layer contains the fields: *id *type *elevation
The line layer contains the fields: *id *start *end *type *length
Limitations:
- MultiGeometry is not supported
- The Z coordinate is ignored
Notes:
- Looped (start = end) generates an error
- *type and *elevation in nodes are not set
- *type' in nodes is set to 'PIPE'
- Epanet node types: JUNCTION/RESERVOIR/TANK
- Epanet link types: PIPE/CVPIPE/PUMP/PRV/PSV/PBV/FCV/TCV/GPV
Tips:
- Verify the network with *Validate*
- The fields of the input layer are preserved. Consider using them to
get the diameter and roughness of the pipe
===
Genera una red epanet a partir de líneas.
La red generada consiste en dos capas: una de nodos y otra de líneas.
Los extremos de línea no distanciados más de la tolerancia se fusionan
en un nodo.
La capa de nodos contendrá los campos: *id *type *elevation
La capa de línea contendrá los campos: *id *start *end *type *length
Limitaciones:
- No se acepta MultiGeometry
- La coordenada Z se ignora
Notas:
- Líneas en bucle (start = end) generan un error
- *type y *elevation en la capa de nodos deben asignarse a posteriori
- *type en la capa de líneas se fija en 'PIPE'
- Epanet node types: JUNCTION/RESERVOIR/TANK
- Epanet link types: PIPE/CVPIPE/PUMP/PRV/PSV/PBV/FCV/TCV/GPV
Consejos:
- Verifique la red con *Validate*
- Los campos de la capa de entrada se conservan. Considere usarlos para
obtener el diámetro y la rugosidad de la tubería
''')
def initAlgorithm(self, config=None):
"""
Define the inputs and outputs of the algorithm.
"""
# INPUT
self.addParameter(
QgsProcessingParameterFeatureSource(
self.INPUT,
self.tr('Line vector layer input'),
types=[QgsProcessing.TypeVectorLine]
)
)
self.addParameter(
QgsProcessingParameterDistance(
self.TOLERANCE,
self.tr('Minimum node separation, otherwise merge them'),
defaultValue=0.001,
minValue=0.0001,
maxValue=1.0
)
)
self.addParameter(
QgsProcessingParameterString(
self.NODE_MASK,
self.tr('Node mask (P-$$-S generates P-01-S)'),
defaultValue='$'
)
)
self.addParameter(
QgsProcessingParameterNumber(
self.NODE_INI,
self.tr('Number of the first node'),
type=QgsProcessingParameterNumber.Integer,
defaultValue=1
)
)
self.addParameter(
QgsProcessingParameterNumber(
self.NODE_INC,
self.tr('Node increment'),
type=QgsProcessingParameterNumber.Integer,
defaultValue=1
)
)
self.addParameter(
QgsProcessingParameterString(
self.LINK_MASK,
self.tr('Link mask (P-$$-S generates P-01-S)'),
defaultValue='$'
)
)
self.addParameter(
QgsProcessingParameterNumber(
self.LINK_INI,
self.tr('Number of first link'),
type=QgsProcessingParameterNumber.Integer,
defaultValue=1
)
)
self.addParameter(
QgsProcessingParameterNumber(
self.LINK_INC,
self.tr('Link increment'),
type=QgsProcessingParameterNumber.Integer,
defaultValue=1
)
)
# ADD NODE AND LINK FEATURE SINK
self.addParameter(
QgsProcessingParameterFeatureSink(
self.NODE_OUTPUT,
self.tr('Network node layer')
)
)
self.addParameter(
QgsProcessingParameterFeatureSink(
self.LINK_OUTPUT,
self.tr('Network link layer')
)
)
def processAlgorithm(self, parameters, context, feedback):
"""
RUN PROCESS
"""
# INPUT
linelayer = self.parameterAsSource(parameters, self.INPUT, context)
tol = self.parameterAsDouble(parameters, self.TOLERANCE, context)
nmask = self.parameterAsString(parameters, self.NODE_MASK, context)
nini = self.parameterAsInt(parameters, self.NODE_INI, context)
ninc = self.parameterAsInt(parameters, self.NODE_INC, context)
lmask = self.parameterAsString(parameters, self.LINK_MASK, context)
lini = self.parameterAsInt(parameters, self.LINK_INI, context)
linc = self.parameterAsInt(parameters, self.LINK_INC, context)
# SEND INFORMATION TO THE USER
feedback.pushInfo('='*40)
crsid = linelayer.sourceCrs().authid()
if crsid:
feedback.pushInfo('CRS is {}.'.format(crsid))
else:
feedback.pushInfo('WARNING: CRS is not set!')
if linelayer.wkbType() == QgsWkbTypes.MultiLineString:
feedback.reportError('ERROR: Source geometry is MultiLineString!')
# READ LINESTRINGS AS WKT
lines = []
for feature in linelayer.getFeatures():
line = []
for point in feature.geometry().asPolyline():
line.append((point.x(), point.y()))
lines.append(line)
for line in lines:
if tools.dist2p(line[0], line[-1]) < tol:
feedback.reportError('ERROR: Looped LineString!')
return {}
# SHOW INFO
feedback.pushInfo('Read: {} LineStrings.'.format(len(lines)))
# CONFIG
def n_format(index):
return tools.format_id(nini + index*ninc, nmask)
def l_format(index):
return tools.format_id(lini + index*linc, lmask)
# CALCULATE NETWORK
nodes, links = tools.net_from_linestrings(lines, tol)
# GENERATE NODE LAYER
newfields = QgsFields()
newfields.append(QgsField("id", QVariant.String))
newfields.append(QgsField("type", QVariant.String))
newfields.append(QgsField("elevation", QVariant.Double))
(node_sink, node_id) = self.parameterAsSink(
parameters,
self.NODE_OUTPUT,
context,
newfields,
QgsWkbTypes.Point,
linelayer.sourceCrs()
)
# ADD FEATURES
ncnt = 0
f = QgsFeature()
for x, y in nodes[:]:
nodeid = n_format(ncnt)
f.setGeometry(QgsGeometry.fromPointXY(QgsPointXY(x, y)))
f.setAttributes([nodeid, '', 0.0])
node_sink.addFeature(f)
ncnt += 1
# SHOW PROGRESS
if ncnt % 100 == 0:
feedback.setProgress(50*ncnt/len(nodes))
# GENERATE LINK LAYER
newfields = QgsFields()
newfields.append(QgsField("id", QVariant.String))
newfields.append(QgsField("start", QVariant.String))
newfields.append(QgsField("end", QVariant.String))
newfields.append(QgsField("type", QVariant.String))
newfields.append(QgsField("length", QVariant.Double))
newfields.extend(linelayer.fields())
(link_sink, link_id) = self.parameterAsSink(
parameters,
self.LINK_OUTPUT,
context,
newfields,
QgsWkbTypes.LineString,
linelayer.sourceCrs()
)
# ADD FEATURES
lcnt = 0
g = QgsFeature()
for f in linelayer.getFeatures():
link = links[lcnt]
linkid = l_format(lcnt)
start = n_format(link[0])
end = n_format(link[1])
poly = []
for x, y in links[lcnt][2][:]:
poly.append(QgsPointXY(x, y))
length = tools.length2d(poly)
attr = [linkid, start, end, 'PIPE', length]
attr.extend(f.attributes())
g.setGeometry(QgsGeometry.fromPolylineXY(poly))
g.setAttributes(attr)
link_sink.addFeature(g)
lcnt += 1
# SHOW PROGRESS
if lcnt % 100 == 0:
feedback.setProgress(50+50*lcnt/len(links))
feedback.pushInfo('Network was generated successfully.')
feedback.pushInfo('Node number: {}.'.format(ncnt))
feedback.pushInfo('Link number: {}.'.format(lcnt))
feedback.pushInfo('='*40)
# PROCCES CANCELED
if feedback.isCanceled():
return {}
# OUTPUT
return {self.NODE_OUTPUT: node_id, self.LINK_OUTPUT: link_id}