Last active
September 3, 2021 12:08
-
-
Save agiudiceandrea/621e4f0f2804e49cbd6f2a4314c0e482 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
""" | |
*************************************************************************** | |
* * | |
* This code is licensed by Andrea Giudiceandrea under CC-BY-SA license * | |
* https://creativecommons.org/licenses/by-sa/3.0/ as a derivative work * | |
* of the code originally published by Jochen Schwarze, under the same * | |
* license, at https://gis.stackexchange.com/a/198329/107272 * | |
* * | |
*************************************************************************** | |
""" | |
from qgis.PyQt.QtCore import QCoreApplication, QVariant | |
from qgis.core import (QgsProcessing, | |
QgsProcessingUtils, | |
QgsFeatureSink, | |
QgsProcessingException, | |
QgsProcessingAlgorithm, | |
QgsProcessingParameterFeatureSource, | |
QgsProcessingParameterFeatureSink, | |
QgsFields, | |
QgsField, | |
QgsFeature) | |
from qgis import processing | |
class AddLineSubnetField(QgsProcessingAlgorithm): | |
""" | |
This is an example algorithm that takes a vector layer and | |
creates a new identical one. | |
It is meant to be used as an example of how to create your own | |
algorithms and explain methods and variables used to do it. An | |
algorithm like this will be available in all elements, and there | |
is not need for additional work. | |
All Processing algorithms should extend the QgsProcessingAlgorithm | |
class. | |
""" | |
# 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. | |
INPUT = 'INPUT' | |
OUTPUT = 'OUTPUT' | |
subNets = [] | |
def tr(self, string): | |
""" | |
Returns a translatable string with the self.tr() function. | |
""" | |
return QCoreApplication.translate('Processing', string) | |
def createInstance(self): | |
return AddLineSubnetField() | |
def name(self): | |
""" | |
Returns the algorithm name, used for identifying the algorithm. This | |
string should be fixed for the algorithm, and must not be localised. | |
The name should be unique within each provider. Names should contain | |
lowercase alphanumeric characters only and no spaces or other | |
formatting characters. | |
""" | |
return 'AddLineSubnetField' | |
def displayName(self): | |
""" | |
Returns the translated algorithm name, which should be used for any | |
user-visible display of the algorithm name. | |
""" | |
return self.tr('AddLineSubnetField') | |
def shortHelpString(self): | |
""" | |
Returns a localised short helper string for the algorithm. This string | |
should provide a basic description about what the algorithm does and the | |
parameters and outputs associated with it.. | |
""" | |
return self.tr("Adds a subnet field to a line type layer.\n" \ | |
"The subnet field will contain the same unique " \ | |
"progressive integer value for all the feature that " \ | |
"are not disjoint (i.e. having any common node or are " \ | |
"intersecting) to the other features.") | |
def initAlgorithm(self, config=None): | |
""" | |
Here we define the inputs and output of the algorithm, along | |
with some other properties. | |
""" | |
# We add the input vector features source. It can have any kind of | |
# geometry. | |
self.addParameter( | |
QgsProcessingParameterFeatureSource( | |
self.INPUT, | |
self.tr('Input layer'), | |
[QgsProcessing.TypeVectorLine] | |
) | |
) | |
# We add a feature sink in which to store our processed features (this | |
# usually takes the form of a newly created vector layer when the | |
# algorithm is run in QGIS). | |
self.addParameter( | |
QgsProcessingParameterFeatureSink( | |
self.OUTPUT, | |
self.tr('Output layer') | |
) | |
) | |
def processAlgorithm(self, parameters, context, feedback): | |
""" | |
Here is where the processing itself takes place. | |
""" | |
# Retrieve the feature source and sink. The 'dest_id' variable is used | |
# to uniquely identify the feature sink, and must be included in the | |
# dictionary returned by the processAlgorithm function. | |
source = self.parameterAsSource( | |
parameters, | |
self.INPUT, | |
context | |
) | |
# If source was not found, throw an exception to indicate that the algorithm | |
# encountered a fatal error. The exception text can be any string, but in this | |
# case we use the pre-built invalidSourceError method to return a standard | |
# helper text for when a source cannot be evaluated | |
if source is None: | |
raise QgsProcessingException(self.invalidSourceError(parameters, self.INPUT)) | |
subnet_field = QgsFields() | |
subnet_field.append(QgsField('subnet', QVariant.Int)) | |
fields = QgsProcessingUtils.combineFields(source.fields(), subnet_field) | |
(sink, dest_id) = self.parameterAsSink( | |
parameters, | |
self.OUTPUT, | |
context, | |
fields, | |
source.wkbType(), | |
source.sourceCrs() | |
) | |
# Send some information to the user | |
feedback.pushInfo('CRS is {}'.format(source.sourceCrs().authid())) | |
# If sink was not created, throw an exception to indicate that the algorithm | |
# encountered a fatal error. The exception text can be any string, but in this | |
# case we use the pre-built invalidSinkError method to return a standard | |
# helper text for when a sink cannot be evaluated | |
if sink is None: | |
raise QgsProcessingException(self.invalidSinkError(parameters, self.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 | |
features = source.getFeatures() | |
flist = [] | |
for f in features: | |
flist.append(f) | |
self.makeSubnets(flist) | |
net = 0 | |
for sn in self.subNets: | |
for f in sn: | |
#print net, f | |
outFeat = f | |
outAttrs = f.attributes() | |
outAttrs.extend([net]) | |
outFeat.setFields(fields) | |
outFeat.setAttributes(outAttrs) | |
sink.addFeature(outFeat, QgsFeatureSink.FastInsert) | |
net += 1 | |
#for current, feature in enumerate(features): | |
# Stop the algorithm if cancel button has been clicked | |
# if feedback.isCanceled(): | |
# break | |
# outFeat = feature | |
# attrs = feature.attributes() | |
# 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. In this case our only result is | |
# the feature sink which contains the processed features, but some | |
# algorithms may return multiple feature sinks, calculated numeric | |
# statistics, etc. These should all be included in the returned | |
# dictionary, with keys matching the feature corresponding parameter | |
# or output names. | |
return {self.OUTPUT: dest_id} | |
def makeSubnets(self, featureList): | |
#print "making subnet ---------------------------------------------------" | |
if len(featureList) > 1: | |
#print [featureList[0]] | |
#print featureList[1:] | |
#print "start finding a subnet" | |
fTest, fRest = self.findSubnet([featureList[0]], featureList[1:]) | |
#print "finished finding a subnet" | |
self.subNets.append(fTest) | |
self.makeSubnets(fRest) | |
else: | |
self.subNets.append(featureList) | |
def findSubnet(self, featTest, featRest): | |
found = True | |
while found: | |
newTestList = [] | |
#print "candidates: ", len(featTest) | |
#print "search in: ", len(featRest) | |
#print "-------------" | |
for fT in featTest: | |
for fR in featRest: | |
if not fT.geometry().disjoint(fR.geometry()): | |
#print "!" | |
newTestList.append(fR) | |
#addRubberBand(fR.geometry()) | |
featTest += newTestList | |
if newTestList == []: | |
found = False | |
else: | |
#print "Found (undis)joining segments" | |
for fn in newTestList: | |
if fn in featRest: | |
featRest.remove(fn) | |
#print "removed ", fn | |
else: | |
pass | |
#print "allready removed ", fn | |
return featTest, featRest |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment